text stringlengths 10 2.61M |
|---|
Vagrant.require_version ">= 1.8"
# Set default provider
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'virtualbox'
# Check to determine whether we're on a windows or linux/os-x host,
# later on we use this to launch ansible in the supported way
# source: https://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-progr... |
module Tartly
class Base
attr_accessor :host, :port, :path
CHECK_WAIT = 1
CHECK = 2
DOWNLOAD = 4
SEED = 8
STOPPED = 16
def initialize(host = nil, port = nil, path = nil)
@config = YAML.load_file(Rails.root + "config/torrent.yml")
@host = host || @... |
# LEARN RUBY THE HARD WAY - 3 EDITION
# ----------------------------------------------------------------------------
# Exercise 11 : Asking Questions
# ------------------------------
# Now it's time to pick up the pace. You're doing a lot of printing to get you
# familiar with typing simple things, but thos... |
require "spec_helper"
describe Paperclip::Validators::AttachmentFileNameValidator do
before do
rebuild_model
@dummy = Dummy.new
end
def build_validator(options)
@validator = Paperclip::Validators::AttachmentFileNameValidator.new(options.merge(
... |
require File.expand_path(File.join(File.dirname(__FILE__), '..', '/spec_helper'))
describe Mailman::MessageProcessor do
def basic_email
"To: mikel\r\nFrom: bob\r\nSubject: Hello!\r\n\r\nemail message\r\n"
end
before do
@router = mock('Message Router')
@processor = Mailman::MessageProcessor.new(:rou... |
# -*- encoding : utf-8 -*-
require 'digest/sha1'
class Admin < ActiveRecord::Base
attr_accessible :email, :hash_pass, :hash_salt, :login, :name, :priv_level, :password
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :message => ": непрваильный формат email"
attr_accessor :p... |
require "spec_helper"
describe AnsiChameleon::TextRendering do
def sequence(effect_name, foreground_color_name=nil, background_color_name=nil)
"[SEQUENCE:#{effect_name}:#{foreground_color_name}:#{background_color_name}]"
end
let(:style_sheet_handler) { stub(:style_sheet_handler, :default_values => default_... |
class UsresController < ApplicationController
# GET /usres
# GET /usres.json
def index
@usres = Usre.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @usres }
end
end
# GET /usres/1
# GET /usres/1.json
def show
@usre = Usre.find(params[:id])
... |
class Admin::AssociationPhotosController < AdminController
def index
@association = Association.find(params[:association_id])
@photos = @association.photos
end
def create
@association = Association.find params[:association_id]
@photo = @association.photos.create(params[:association_photo])
end... |
require 'stringio'
module Netlink
module CodingHelpers
class << self
def included(base)
base.extend(ClassMethods)
end
end
module ClassMethods
def decode(bytes, *args)
ret = new
ret.decode(bytes, *args)
ret
end
def read(io, *args)
re... |
module ApplicationHelper
require 'net/http'
include ActionView::Helpers::NumberHelper
require 'json'
def full_title(page_title = '')
base_title = 'Artist Portal'
if page_title.empty?
base_title
else
page_title + ' | ' + base_title
end
end
# Returns a hash of the top five top_so... |
# == Schema Information
#
# Table name: albums
#
# id :integer(4) not null, primary key
# contact_id :integer(4)
# title :string(255)
# date :datetime
# created_at :datetime
# updated_at :datetime
#
class Album < ActiveRecord::Base
# belongs_to :contact
# #has_many :images
#
#... |
class Forummessage < ActiveRecord::Base
belongs_to :user
belongs_to :forumtopic
has_many :forumreports, :dependent => :destroy
validates_length_of :raw, :minimum => 3, :too_short => "Je bericht is te kort"
end
|
require 'rails_helper'
RSpec.describe ShipMethod, type: :model do
let (:carrier) { FactoryGirl.create :carrier }
let (:other_carrier) { FactoryGirl.create :carrier }
let (:attributes) do
{
carrier_id: carrier.id,
description: 'Really Fast',
abbreviation: 'RF',
calculator_class: 'TestS... |
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy, :banning, :real_code]
before_action :only_admin, only: [:index]
before_action :correct_user, only: [:edit, :update, :real_code]
before_action :user_has_number, only: [:real_code]
before_action :authe... |
require 'test_helper'
class ComboTest < ActiveSupport::TestCase
def setup
@combo = combos(:one)
end
test_fixtures
test_dependent_associations(destroy: [ComboItem, Acquirement])
test 'Parent requirement should have no other combos' do
combo_params = {
user: @combo.user,
order: @combo.ord... |
# Implementation of a list using a Native array --> ruby does this automatically
class ArrayList # Ruby's array is an ArrayList. We are simulating what a Ruby array does by showing what happens with the native array within the Ruby array.
def initialize
@storage = [nil,nil,nil,nil,nil] # this array has a capaci... |
class Protocol < ApplicationRecord
has_many :protocol_drugs
has_many :facility_groups
before_create :assign_id
validates :name, presence: true
validates :follow_up_days, numericality: true, presence: true
auto_strip_attributes :name, squish: true, upcase_first: true
def as_json
super.tap do |json... |
module FlashFlow
module TimeHelper
def with_time_zone(tz_name)
prev_tz = ENV['TZ']
ENV['TZ'] = tz_name
yield
ensure
ENV['TZ'] = prev_tz
end
end
end
|
# Gestion des Qd/Rd dans les snippets
require_relative 'direct'
class Qrd
class << self
#---------------------------------------------------------------------
# Snippets
#---------------------------------------------------------------------
# => Code Snippet pour la référence à une QD/R... |
class GroupsController < ApplicationController
before_action :authenticate_user!
def index
@user = current_user
@groups = @user.groups
@invitations = @user.invitations
end
def new
@user = current_user
@group = Group.new
end
def create
@admin = Admin.create({user_id: current_user... |
# encoding: utf-8
require "securerandom"
module Antelope
module Generation
class Recognizer
# Defines a rule. A rule has a corresponding production, and a
# position in that production. It also contains extra
# information for other reasons.
class Rule
# The left-hand side of... |
require 'rails_helper'
RSpec.describe "API::V1::Airports", type: :request do
describe "GET /index" do
it "returns http success" do
get "/api/v1/airports/"
expect(response).to have_http_status(:success)
end
it "filters airports based on countries" do
create(:airport, :fra)
zurich_... |
require 'rails_helper'
RSpec.describe 'Tweet/edit', type: :request do
let!(:user) { create(:user) }
let!(:tweet) { create(:tweet, user: user) }
context 'ログインしているユーザーの場合' do
before do
sign_in user
end
it 'レスポンスが正常に表示されること' do
get edit_tweet_path(tweet)
expect(response).to render_tem... |
include_recipe "db_mysql::setup_block_device"
database "/mnt/storage" do
provider "database"
storage_type "ros"
cloud "rackspace"
rackspace_user node[:db_mysql][:backup][:rackspace_user]
rackspace_secret node[:db_mysql][:backup][:rackspace_secret]
storage_container node[:db_mysql][:backup][:storage_conta... |
FactoryBot.define do
factory :project do
meeting
councilman
sequence(:name) { Faker::Hipster.sentence }
project_kind
sequence(:description) { Faker::Lorem.paragraph(2) }
end
end
|
# frozen_string_literal: true
require 'test_helper'
EXPECTED = "XPBsjgKKG2HqsKBhWA4uQw"
YOUTUBE_CHANNEL_VARIATIONS = [
"https://www.youtube.com/channel/UCXPBsjgKKG2HqsKBhWA4uQw",
"youtube.com/channel/UCXPBsjgKKG2HqsKBhWA4uQw",
"youtube.com/channel/XPBsjgKKG2HqsKBhWA4uQw",
"UCXPBsjgKKG2HqsKBhWA4uQw",
EXPECTE... |
module NewGoogleRecaptcha
class Railtie < ::Rails::Railtie
initializer 'new_google_recaptcha.helpers' do
ActiveSupport.on_load :action_view do
ActionView::Base.send :include, NewGoogleRecaptcha::ViewExt
end
end
end
end
|
Rails.application.routes.draw do
# root "attractions#index"
resources :session, only: [:create]
resources :users, only: [:create, :destroy, :update]
resources :attractions, only: [:index, :create, :destroy, :show, :update]
resources :reviews, only: [:create, :destroy]
resources :otm_attractions, only: [:ind... |
class AddStatusColumnToRendezvousRegistrations < ActiveRecord::Migration
def change
add_column :rendezvous_registrations, :status, :string
add_index :rendezvous_registrations, :status
end
end
|
class Api::V1::NotesController < ApplicationController
def index
@notes = Note.all
render json: @notes
end
def create
@note = Note.create(title: params[:title], content: params[:content])
render json: @note, status: 201
end
def new
@note = Note.new
end
def edit
@note = Note.fin... |
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/readmill/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'readmill'
s.version = Readmill::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Andrew Thorp']
s.email = ['andrewpthorp@gmail.com']
s.homepage =... |
require "rails_helper"
RSpec.describe InvestigationactionsController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(get: "/investigationactions").to route_to("investigationactions#index")
end
it "routes to #new" do
expect(get: "/investigationactions/new").to route_t... |
require 'spec_helper'
describe StripeDetailsController do
after(:all) do
User.delete_all
StripeDetail.delete_all
end
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = FactoryGirl.create(:user)
FactoryGirl.create(:configuration_setting)
@user.confirm! # set a... |
RSpec.describe ConcreteHolidays::Christmas do
let(:holiday) { ConcreteHolidays::Christmas }
let(:year) { 2015 }
it "calculates christmas day" do
expect(holiday.date(year)).to eq(Date.new(year,12,25))
end
end
|
class ProviderNotNullableUser < ActiveRecord::Migration[5.2]
def change
change_column :users, :provider, :string, null: false
end
end
|
class Avenger
@@all = []
attr_reader :weapon, :name
def initialize(name, weapon)
@name = name
@weapon = weapon
@@all << self
end
def self.all
@@all
end
def self.most_appearances # return the avenger
all.max do |a, b|
a.appearances.count <=> b.appearances.count
end
end
... |
class RolesController < ApplicationController
before_action :set_role, only: [:show, :edit, :update, :destroy]
# GET /roles
# GET /roles.json
def index
respond_to do |format|
format.html
format.json { render json: RolesDatatable.new(view_context) }
end
end
# GET /roles/1
# GET /roles/1.json
def show... |
class RemoveTypeFromCategories < ActiveRecord::Migration[5.0]
def change
remove_column :categories, :type
end
end
|
class AddMaxQuantityToOrderComboItem < ActiveRecord::Migration
def change
add_column :order_item_combos, :max_quantity, :integer, :default => 0
end
end
|
#
# Copyright:: Copyright (c) 2016-2017 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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/LICE... |
require 'rails_helper'
RSpec.describe 'Profile SKills API' do
let!(:user) { create(:user) }
let!(:member_source_type) { create(:member_source_type)}
let!(:member_type) { create(:member_type) }
let!(:account_status_type) { create(:account_status_type)}
let!(:member) { create(:member, member_source_type_id:mem... |
#!/usr/local/bin/ruby
require 'rubygems'
require 'xmlsimple'
@home_dir = File.expand_path("~")
require File.join(@home_dir, 'backpack')
def format_time(t)
t.strftime("%B %d, %Y at %I:%M %p")
end
command = ARGV.shift
home_dir = ENV['HOME']
config_path = File.join(home_dir, '.backpack.yml')
if !File.exist?(config_... |
sum = 0
i= 1
while i <= 5
sum += i
i += 1
end
puts sum
=begin
这与使用 for 语句的程序有细微的区别。首先,变量 i 的条件指定方式不一样。
使用 for 语句时通过 1..5 指定条件的范围,while 语句则使用比较运算符 <=,指定“i 小于等于 5 时(循环)”这一条件。
另外,i 的累加方式也不一样。while 语句的例子在程序中直接写出了 i 是如何进行加 1
处理的,即 i += 1,而 for 语句的例子并不需要在程序中直接写如何对 i 进行操作,自动在每次循环后对 i 进行加 1 处理。
=end |
loop do
puts "Stop pestering you? (yes/no)"
answer = gets.chomp
if answer.downcase == "yes"
break
end
puts "Okedoke!"
end |
require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = "Tetris"
end
test "should get index" do
get root_url
assert_response :success
assert_select "title", "#{@base_title}"
end
test "should get store" do
get store_path
assert... |
require 'rails_helper'
RSpec.describe Note, type: :model do
before(:each) do
@note = Note.first
end
it "belongs to a user" do
expect(@note.user.username).to eq(User.first.username)
end
it "belongs to an item" do
expect(@note.item.title).to eq("casserole")
end
end
|
require_relative 'lxc/version'
require_relative 'lxc/line'
require_relative 'lxc/lines'
require_relative 'lxc/file'
require_relative 'lxc/directory'
require_relative 'lxc/index'
module Linux
module Lxc
def self.numeric_prefix_order(data)
data.sort do |a,b|
a_m = a.match(/^(\d+)(.*)$/)
b_m =... |
require 'data_mapper'
require 'dm-postgres-adapter'
require_relative './peep'
class User
include DataMapper::Resource
property :id, Serial
property :email, String, :required => true, :unique => true, :format => :email_address
property :password, String, :required => true
property ... |
require 'rails_helper'
describe Meta::GamesController do
before(:all) do
@admin = create(:user)
@admin.grant(:edit, :games)
@user = create(:user)
end
describe 'GET #index' do
it 'succeeds for authorized user' do
sign_in @admin
get :index
expect(response).to have_http_status(... |
class Timetable < ApplicationRecord
belongs_to :user
has_many :timetables_courses
has_many :courses, through: :timetables_courses
end
|
#!/usr/bin/env ruby
# frozen_string_literal: true
# Merge a file with its includes, pass filename as first argument
TMP = ENV['TMP'] || '.tmp.mtl'
unless ARGV.size == 1
puts "usage: #{File.basename(__FILE__)} [filename]"
abort
end
file = ARGV.first
BASE_DIR = File.dirname(file)
BASE_DIR_LIB = File.dirname(File.... |
class Plaza < ApplicationRecord
belongs_to :user
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :name, presence: { message: "Please add a name" }, length: { maximum: 20}, uniqueness: true
mount_uploader :foto, PictureUploader
mount_uploader :foto_cabecera, PictureUpl... |
require 'spec_helper'
describe ApnClient::Connection do
describe "#initialize" do
it "opens an SSL connection given host, port, certificate, and certificate_passphrase" do
if certificate_exists?
connection = ApnClient::Connection.new(valid_config)
connection.config.should == valid_config_wi... |
require "osdn/repository/uploader/version"
require "thor"
require "osdn-client"
require "find"
module Osdn
module Repository
module Uploader
class Command < ::Thor
desc "upload ", "Upload files under repository"
option :project
option :repository
def upload
OSDNC... |
class Profile < ActiveRecord::Base
belongs_to :user
validates :hometown, :presence => {:message => 'Please fill in home town!'}
has_attached_file :photo,
:styles => {
:thumb=> "100x100#",
:small => "400x400>" },
:path => ":rails_root/public/images/photos/:id/:style/:basename.:exten... |
class TurnsController < ApplicationController
def new
@plant = Plant.find(params[:id])
@turn = Turn.new(plant: @plant)
flash[:notice] = "You win!" if @plant.has_fruit?
end
def create
@plant = Plant.find(params[:id])
@turn = Turn.new(grow_params.merge(plant: @plant))
growth = GreenhouseSe... |
Pod::Spec.new do |s|
s.name = 'OCMockito'
s.version = '1.4.0'
s.summary = 'OCMockito is an Objective-C implementation of Mockito, supporting creation, verification and stubbing of mock objects.'
s.homepage = 'https://github.com/jonreid/OCMockito'
s.license = 'MIT'
s.author = { 'Jon Reid... |
require_relative "blame_analyzer/author"
require_relative "blame_analyzer/summary_printer"
require_relative "git/git"
module BlameAnalyzer
class Analyzer
attr_reader :loc, :files
def initialize
@authors = Hash.new { |h,k| h[k] = Author.new(abbreviation: k) }
@loc = 0
@files = 0
@git... |
class AddAdminstratorIdToProductionUnits < ActiveRecord::Migration
def change
add_column :production_units, :administrator_id, :integer
add_index :production_units, :administrator_id
end
end
|
require 'csv'
class Contact
attr_accessor :name, :email
def initialize(name, email)
@name = name
@email = email
end
class << self
def all
# TODO: Return an Array of Contact instances made from the data in 'contacts.csv'.
list = Array.new
CSV.foreach('contacts.csv') do |r... |
class AddColumnsToPlayers < ActiveRecord::Migration[6.0]
def change
add_column :players, :level, :string
add_column :players, :avatar_small, :binary
end
end
|
# frozen_string_literal: true
class UsersController < ApplicationController
before_action :authenticate_user!
before_action :set_user, only: %i[edit update show]
before_action :edit_auth, only: %i[edit update]
def index
@users = User.with_attached_image
end
def edit; end
def update
if @user.up... |
class CreateServices < ActiveRecord::Migration
def change
create_table :services do |t|
t.references :route, index: true, foreign_key: true
t.references :payment_type, index: true, foreign_key: true
t.string :observation
t.references :client, index: true, foreign_key: true
t.referenc... |
class MergePersonToUsers < ActiveRecord::Migration
def up
User.reset_column_information
Person.all.each do |person|
user = User.find_or_initialize_by(email: "#{person.english_name.downcase.tr(" ", ".")}@think-bridge.com")
user.person_id = person.id
user.name = person.e... |
class Feedback < ActiveRecord::Base
validates :feedback_name, presence: true
validates :feedback_text, presence: true
end
|
class Opendata::Appfile
include SS::Document
include SS::Relation::File
include Opendata::TsvParseable
include Opendata::AllowableAny
include Opendata::Common
attr_accessor :workflow, :status
seqid :id
field :filename, type: String
field :text, type: String
field :format, type: String
embedded_... |
require "application_system_test_case"
class StockLogsTest < ApplicationSystemTestCase
setup do
@stock_log = stock_logs(:one)
end
test "visiting the index" do
visit stock_logs_url
assert_selector "h1", text: "Stock Logs"
end
test "creating a Stock log" do
visit stock_logs_url
click_on "... |
Given /^User "([^"]*)" with password "([^"]*)" exists$/ do |email, pass|
FactoryGirl.create :user, :email => email, :password => pass
end
Then /^I go to the login page$/ do
visit new_signed_user_session_path
end
Then /^I fill in login with "([^"]*)"$/ do |email|
fill_in tr('simple_form.labels.signed_user.email'... |
RSpec::Matchers.define :have_correct_syntax do
match do |file_path|
source = File.read(file_path)
extension = File.extname(file_path)
case extension
when '.rb', '.rake'
check_ruby_syntax(source)
when '.rhtml', '.erb'
check_erb_syntax(source)
when '.haml'
check_ham... |
require 'cheeky-pi/animation/cycle'
module CheekyPi
module Animation
class Throb < Cycle
def initialize(duration, light, options={})
super
@to = options[:to]
@from = options[:from]
@wave = options[:type] || :triangle
end
def animate
blend_percent = se... |
class Article < ActiveRecord::Base
attr_accessible :title, :content, :category_id
belongs_to :category
paginates_per 13
default_scope order('created_at DESC')
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context '新規登録できるとき' do
it '全て入力されていれば登録できる' do
expect(@user).to be_valid
end
it 'emailに@が含まれていれば登録できる' do
@user.email = 'aaa@aaa'
exp... |
# frozen_string_literal: true
require 'test_helper'
class PhonePresenterTest < ActiveSupport::TestCase
test 'types returns an array' do
phone = StubPhone.new
types = PhonePresenter.new(phone, nil).types
assert_equal Array, types.class
end
test 'persons_list returns an array' do
phone = StubPhon... |
require "rails_helper"
describe Shop do
let(:shop_params) { { id: 1, name: "Loja Teste", zip: "03320000" } }
subject { Shop.new(shop_params) }
it "is valid with valid params" do
expect(subject).to be_valid
end
it "is invalid without a name" do
shop_params.delete(:name)
expect(subject).to_not b... |
#
# Assignment 2
#
#
# Question 1
#
def factorial n
return (1..n).reduce(:*)
end
#tests
puts "factorial: #{factorial 5}"
puts "factorial: #{factorial 10}"
puts "factorial: #{factorial 24}"
#
# Question 2
#
def add_list list
return list.reduce(:+)
end
#tests
puts "add_list: #{add_list [1, 1, 1, 1]}"
puts "add_list:... |
class Designer::DesignsController < ApplicationController
def show
@design = current_user.designs.find(params["format"])
end
def edit
@design = current_user.designs.find(params["format"])
end
def update
@design = current_user.designs.find(params["id"])
@design.update(design_params)
... |
class FeatureVectorWorker
include Sidekiq::Worker
def perform(class_name, id)
class_name.constantize.find(id).send(:update_feature_vectors!)
end
end
|
require File.expand_path("../helper", __FILE__)
describe Tinify do
dummy_file = File.expand_path("../examples/dummy.png", __FILE__)
describe "key" do
before do
stub_request(:get, "https://api:fghij@api.tinify.com").to_return(status: 200)
end
it "should reset client with new key" do
Tinify... |
require 'rails_helper'
feature 'Delete answer' , '
As an Author of answer
I want to delete my answer
' do
given(:question_author) { create(:user) }
given(:question) { create(:question, user: question_author) }
given(:answer_author) { create (:user) }
given(:answer) {create :answer, question: question,... |
#!/usr/bin/env ruby
# Author:: David Rio Deiros (mailto:deiros@bcm.edu)
# Copyright:: Copyright (c) 2008 David Rio Deiros
# License:: BSD
#
# vim: tw=80 ts=2 sw=2
require 'find'
require 'date'
# Namespace for the MiniAnalysis project for SLX
module MiniAnalysis
# Put all the config stuff here
module CFG
... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
# Make sure we have the vagrant-hostmanager plugin. No point in going forward with out it.
if !(Vagrant.has_plugin?('vagrant-hostmanager'))
fail_with_message "vag... |
# frozen_string_literal: true
class FieldShowComponent < ViewComponent::Base
def initialize(label:, value:)
@label = label
@value = value
end
end
|
require_relative '../conversions.rb'
describe "conversions" do
describe '#ounces_to_grams' do
it 'given zero, returns 0.0' do
grams = ounces_to_grams(0)
expect(grams).to eq(0.0)
end
end
describe '#meal_choice' do
it 'should default to meat for the protein' do
expect(meal_choice("br... |
# -*- coding: utf-8 -*-
require 'spec_helper'
describe "Glossaries" do
describe "index" do
context "layout, without glossaries" do
before(:each){ visit glossaries_path }
it "have a title" do
page.should have_title('Glossaries')
end
it "has a table for the glossaries" do
... |
class Event < ApplicationRecord
has_many :attendances, foreign_key: 'attended_event_id'
has_many :users, through: :attendances
belongs_to :admin, class_name: 'User'
validates :start_date,
presence: true
validates :duration,
presence: true,
numericality: { greater_than: 0, only_integer: true}... |
class Trip < ApplicationRecord
has_many :locations, dependent: :destroy
accepts_nested_attributes_for :locations, allow_destroy: true, reject_if: proc { |att| att['latitude'].blank? } #, 'longitude' Check how to add both
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2020 MongoDB Inc.
#
# 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... |
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,4,8],
[2,4,6],
[0,3,6],
[2,5,8],
[1,4,7]]
def play(board)
until over? board
turn board
#the following lines were added to try to help tests pass
if ((won? board) || (over? board))
break
end
end
the_winner = winner b... |
module Kagishi
class Issuer
attr_reader :email, :payload
def initialize(email, payload: {})
@email = email
@payload = payload
end
def issue_token
new_payload = payload.merge({ email: email, exp: Time.now.utc.to_i + ttl })
JWT.encode new_payload, secret, algorithm
end
... |
require 'rails_helper'
RSpec.describe User, type: :model do
context 'validations' do
before { FactoryBot.build(:user) }
it { is_expected.to validate_presence_of(:first_name) }
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to validate_presence_of(:password) }
it { is_expecte... |
class Entity
include Mongoid::Document
extend DocumentMethods
field :name, type: String
belongs_to :app
embeds_many :data_fields
has_many :views
has_many :relationships, inverse_of: :entity1
has_many :relationships, inverse_of: :entity2
has_many :records
end
|
=begin
Description :
Old-school Roman numerals.
In the early days of Roman numerals, the Romans didn’t bother with any of this new-fangled subtraction “IX” nonsense.
No sir, it was straight addition, biggest to littlest—so 9 was written “VIIII,” and so on.
Write a method that when passed an integer between 1 and 3000 (... |
# frozen_string_literal: true
require "htmlentities"
module Foxy
module Html
class Object
DECODER = HTMLEntities.new
attr_reader :nodes
def initialize(html)
@nodes =
if html.nil?
[]
elsif html.respond_to?(:nodes)
html.nodes
elsif ... |
require 'rails_helper'
RSpec.describe DonationForm, type: :model do
before do
@user = FactoryBot.build(:user )
@item = FactoryBot.build(:item )
@donation_form = FactoryBot.build(:donation_form, user_id:@user.id, item_id: @item.id)
end
describe '商品購入登録' do
context '商品購入登録がうまくいくとき' do
it "... |
# ****************************************************************************
#
# Copyright (c) Microsoft Corporation.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you ... |
class Post < ActiveRecord::Base
validates :author_id, :receiver_id, :body, presence: true
belongs_to :author,
primary_key: :id,
foreign_key: :author_id,
class_name: :User
belongs_to :receiver,
primary_key: :id,
foreign_key: :receiver_id,
class_name: :User
has_many :comments
has_man... |
class PropertiesFile
PARAM_REGEX = %r/\A([^=]+)=(.*)\z/
def self.read(path)
File.open(path, 'r') do |file|
parse(file)
end
end
def self.parse(properties_file)
hash = {}
while line = properties_file.gets
match = PARAM_REGEX.match(line.chomp)
hash[match[1].strip] = match[2].str... |
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: prefinery 0.2.1 ruby lib
Gem::Specification.new do |s|
s.name = "prefinery"
s.version = "0.2.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") ... |
namespace :upload do
desc <<~HERE_DOC
Upload files. Show full description with: cap -D upload:files
Use 'restart' to restart the server
Use 'all' to upload all changes files not staged for commit (git diff --name-only)
cap production upload:files README.md
cap production ROLES=db upload:files REA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.