text
stringlengths
10
2.61M
class AddUserCountToGames < ActiveRecord::Migration[5.2] def change add_column :games, :max_users, :integer, default: 0 end end
class Song attr_reader:name,:artist,:duration def initialize(name,artist,duration) @name=name @artist=artist @duration=duration end attr_writer:duration def duration_in_minutes @duration/60.0 end def duration_in_minutes @duration = (new_duration*60).to_i end end song = Song.new("B","k",200) song.dura...
module Tablette class HTMLRenderer def element=(element) end def produce_element(tag, attributes, content) content = content.join if content.kind_of? Array buffer = "<#{tag}" if attributes.any? buffer << " #{to_html_args(attributes)}" end buffer << ">#{con...
class AnswerTemplate < ActiveRecord::Base has_and_belongs_to_many :questions has_many :answer_options_answer_templates, -> { order "answr_options_answer_templates.created_at" } has_many :answer_options, through: :answer_options_answer_templates, join_table: 'answr_options_answer_templates' belongs_to :display_t...
require "spec_helper" RSpec.describe "Day 22: Wizard Simulator 20XX" do let(:runner) { Runner.new("2015/22") } describe "Part One" do let(:solution) { runner.execute!(input, part: 1, HERO_STATS: [10, 0, 250]) } let(:input) { "Hit Points: 13\nDamage: 8" } it "finds the optimal strategy" do expec...
ruby '2.2.2' source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.1' # Use postgresql as the database for Active Record gem 'pg', '~> 0.17.1' gem 'pg_search', '~> 0.7.8' # Pagination gem 'will_paginate', '~> 3.0.7' # Build JSON APIs with ease. Read more: h...
require 'test_helper' class ArtistsControllerTest < ActionController::TestCase def setup @artist_no_image = artists(:one) @artist_with_songs = artists(:two) @artist_no_songs = artists(:three) end test "should list all artists" do get :index assert_response :success assert_not_nil ...
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "rmmseg-cpp" spec.version = "0.2.9" spec.authors = ["pluskid,seoaqua,ChienliMa"] spec.email = ["pluskid@gmail.com,seoaqua@qq.com,maqianlie@gmail.com"] spec.summary ...
class FakeGithub def self.activity self end def self.events self end def self.repository(user_name, repo_name) json_object = JSON.generate( self.json_for_user_and_repo(user_name, repo_name) ) json_string = JSON.parse(json_object) [Hashie::Mash.new(json_string)] end def se...
module Api module V2 class DepartmentsController < ApplicationController before_action :authenticate_api_access_token, only: [:index, :show] before_action :authenticate_api_modify_token, only: [:create, :update, :destroy] respond_to :json def index ...
require 'colorize' require 'io/console' class Display attr_accessor :cursor, :board KEY = { "w" => :up, "a" => :left, "s" => :down, "d" => :right, "\u0003" => :ctrl_c } MOVES = { left: [0, -1], right: [0, 1], up: [-1, 0], down: [1, 0] } def initialize(board) @board ...
class UsersController < ApplicationController before_action :authenticate_user! before_action :set_user, except: [:edit] before_action :like_users, only: [:show, :bought_products, :sold_products] def show @saling_products = User.find(params[:id]).saling_products end def bought_products @bought...
class Membership < ApplicationRecord belongs_to :fund belongs_to :user validates :allocation_share, numericality: { greater_than: 0 } def allocation_share_percentage ((allocation_share / fund.total_size) * 100).round(2) end end
class GoalServices::SessionsHistoryForUserTimelineBuilder def initialize(goal, viewing_user) @goal = goal @viewing_user = viewing_user end def build { date_labels: date_labels, scores: scores, # current_id: @goal_session.id, # session_ids: session_ids } end private ...
# # Cookbook Name:: zabbix-server # Recipe:: api # # install libraries and tools #%w{ # gcc # openssl-devel # git #}.each do |pkg| # package pkg do # action :install # end #end package "git" do action :install end ## git clone rbenv #git "/home/#{node["zabbix-server"]["user"]}/.#{node["zabbi...
FactoryGirl.define do factory :remote_team_group_statistic, class: Hash do id { generate :team_id } team_id { id } games_played { generate :integer } games_won { generate :integer } games_lost { generate :integer } games_draw { generate :integer } ignored { generate :string } initia...
# # Author:: Matt Eldridge (<matt.eldridge@us.ibm.com>) # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # module Fog module Softlayer class Compute class Mock def get_bare_metal_servers response = Excon::Response.new response.body = @bar...
module Rbooks require "uri" require "openssl" require "net/http" require "json" require "forwardable" class Book extend Forwardable DEFAULT_OPT = {format: "json", formatVersion: "2"}.freeze REQUIRE_CONCAT = [:title, :author, :publisher, :isbn, :booksGenreId].freeze class << s...
loop do puts 'Should I stop looping?' answer = gets.chomp break if answer == 'yes' end # modify the code so the loop stops iterating when the user inputs 'yes'
#!/usr/bin/ruby require "rubygems" require "twitter" require "prowler" require "active_support/core_ext" SHOW = ["Colbert Report", "Daily Show"] #, "Colbert Report"] NUM_TIX = 4 MONTH = "May" DAYS = [26] LOG_FILE = __FILE__ + ".log" PROWL_API = "910b7bb7022099798d50f9356d07c1ec2e8425d2" if File.exists?(LOG_...
require 'spec_helper' describe 'ssh::config_entry' do mandatory_params = { owner: 'test_owner', group: 'test_group', path: '/test/path', host: 'test_host', } let(:title) { 'example' } let(:params) { mandatory_params } context 'with no paramater is provided' do let(:params) { {} } it...
module Auth::Behavior::Core::ControllerExtensions::CurrentUser def self.included(base) base.send(:hide_action, :current_user_from_session, :timeout_current_session, :authenticate_with_persistence_token, :authenticate_with_single_access_token, :authenticate_with_session_cookie, :authenticate_current_...
Rails.application.routes.draw do root "wing_orders#index" resources :wing_orders, only: [:index, :new, :create] end
class DropColumnsFromAd2sTwo < ActiveRecord::Migration def change remove_column :ad2s, :impressions remove_column :ad2s, :spend remove_column :ad2s, :date_start remove_column :ad2s, :date_stop end end
module CDI module V1 class SimpleGameItemAnswerSerializer < ActiveModel::Serializer root false attributes :id, :game_item_id, :user_id, :correct, :reply_word, :created_at, :updated_at end end end
Sequel.migration do up do create_table(:channels) do primary_key :id String :name, default: false # do not respond to channel Bool :disabled, default: false # Auto modes Bool :auto_voice, default: false # Ignore String :ignore_plugins, null: true String :ig...
require 'base64' require 'json' require 'net/http' require 'uri' require 'cgi' module Mixpanel class ActivityLogger BASE_ENDPOINT = 'http://api.mixpanel.com' TRACK_ENDPOINT = "#{BASE_ENDPOINT}/track/" ENGAGE_ENDPOINT = "#{BASE_ENDPOINT}/engage/" IMPORT_ENDPOINT = "#{BASE_ENDPOINT}/import/" d...
class CreateCharacterRaces < ActiveRecord::Migration def change create_table :character_races do |t| t.references :character, index: true t.integer :basespeed t.string :languages t.text :description t.timestamps end end end
class Api::V1::ConversationsController < ApplicationController skip_before_action :authorize, only: [:index, :create] # def index # conversations = Conversation.all # render json: conversations # end def show user = User.find(params[:id]) conversations = user.conver...
# frozen_string_literal: true require 'jiji/test/test_configuration' require 'jiji/test/data_builder' describe Jiji::Model::Trading::TickRepository do include_context 'use container' let(:repository) { container.lookup(:tick_repository) } it 'fetch で tickの一覧を取得できる' do ticks = repository.fetch(%i[EURJPY USD...
class PrimaryComment < ApplicationRecord belongs_to :user belongs_to :link has_many :secondary_comments end
class SurveyUser < ActiveRecord::Base attr_accessible :survey_id, :user_id belongs_to :survey belongs_to :user end
require 'open3' require 'msgpack' class ChunkTest def initialize(host, port) @host = host @port = port @cmd = "nc" @term = false end def run Signal.trap(:INT){ @term = true } Open3.popen3("#{@cmd} #{@host} #{@port}") do |stdin, stdout, stderr, wait_thr| begin i = ...
class Pokemon < ApplicationRecord validates :name, :main_ability, :main_type, presence: true validates :main_type, inclusion: { in: %W(bug electric fairy fighting fire flying grass ground ice normal poison psychic rock steel water) } validates :name, uniqueness: true has_many :teams, dependent: :destroy has_...
class PayerBill < ApplicationRecord belongs_to :bill belongs_to :payer, :class_name => 'User' #validates :amount, numericality: {greater_than: 0.00}, presence: true end
require 'spec_helper' RSpec.describe OmniauthCallbacksController, type: :controller do # describe "#annonymous user" do # context "when facebook email doesn't exist in the system" do # before(:each) do # stub_env_for_omniauth # get :facebook # @user = User.where(:email => "ghos...
require 'rails_helper' RSpec.describe 'User Exams API', type: :request do # initialize test data let!(:user) { create(:user) } let!(:exam) { create(:exam) } let!(:user_exams) { create_list(:user_exam, 20, user_id: user.id, exam_id: exam.id) } let(:user_id) { user.id } let(:exam_id) { exam.id } let(:id) ...
class Photo < ApplicationRecord mount_uploader :picture, PictureUploader belongs_to :user belongs_to :place end
class Tile def initialize(x, y) @x = x @y = y end def x @x end def y @y end def passable @passable end def empty @passable = true end def wall @passable = false end def north @y+1 end def east @x+1 end def south @y-1 end def west ...
class Invoice < ApplicationRecord belongs_to :customer, class_name: "Company" belongs_to :sales_order has_many :invoiced_items validates :customer_id, numericality: { greater_than: 0 } validates :sales_order_id, numericality: { greater_than: 0 } validates :invoice_dt, presence: true validates :net_cost, ...
require 'liquid' module TackleBox module Email class Template module Tags class RandomDate < Liquid::Tag def render(context) today = Date.today return today.strftime("%b #{rand(today.day - 1) + 1}") end end end end end end Liquid::...
class InstructorReviewsController < ApplicationController def new if !user_signed_in? flash[:error] = "Must be signed in to review an instructor." redirect_to root_path end @review = InstructorReview.new @instructor_id = params[:instructor_id] @review.instructor = Instructor.find(params[...
module NotificationSystem class Event < ActiveRecord::Base belongs_to :source, :polymorphic => true serialize :data def self.trigger(attributes = {}) source = attributes[:source] data = attributes.reject { |key,value| key == :source } self.create(:source => attributes[:source], :dat...
require 'amorail/entities/leadable' module Amorail class TaskType < Amorail::Entity amo_names 'task_types' amo_field :name, :code, :id validates :name, presence: true def self.remote_url(name = '') '/private/api/v2/json/accounts/current/task_types' end def self.body_response(respons...
xml.rss(RSS_SPEC) do xml.channel do xml.title "Latest Arts | 89.3 KPCC" xml.link latest_arts_url xml.atom :link, href: latest_arts_url(format: :xml), rel: "self", type: "application/rss+xml" xml.description "The latest arts & life articles from KPCC's award-winning news team." xml ...
class Board attr_accessor :current_player, :board, :error_message, :en_passant def initialize(white, black, board = self.empty_board, current_player = "white") @board = board #graveyards represent the pieces each player has captured. @white_player = [white, "white"] @white_graveyard = [] ...
require 'bowling_scorecard' describe Bowling_scorecard do before do @bowling_scorecard = Bowling_scorecard.new end context 'simple game' do it ' when there are no pins hit, has a gutter game' do 20.times { subject.roll(0) } expect(subject.score).to eq(0) end it 'can count the knock...
class Favorite < ApplicationRecord belongs_to :user, optional: true #加えた belongs_to :user_info end
require_relative 'spec_helper' describe "Trip class" do describe "initialize" do before do start_time = Time.parse('2015-05-20T12:14:00+00:00') end_time = start_time + 25 * 60 # 25 minutes @trip_data = { id: 8, passenger: RideShare::User.new( id: 1, name: "A...
module FacilitiesManagement::Supplier::DashboardHelper def accepted_page ['accepted', 'live', 'not signed', 'withdrawn'] end SUPPLIER_STATUS = { declined: 'Declined', expired: 'Not responded', not_signed: 'Not signed', withdrawn: 'Withdrawn' }.freeze def page_definitions @page_definitions ||= { ...
require 'rubygems' require 'json' class XTParser def handleLoadPackets packet_file = File.read(__dir__ + '/PACKETS.json') packets = JSON.parse(packet_file) @xtPackets = packets end def parseData(data) if data.respond_to?(:to_str) packets = data.split('%') if packets.count < 3 @parent.logger.wa...
class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.text :comment, null:false t.integer :user_id, null:false t.integer :company_id, null:false t.integer :based_opinion, default:1 t.integer :down_votes, default:0 t.integer :status, default:1...
class WelcomeController < ApplicationController def index @users = User.ordered end end
# $ rails generate migration add_picture_to_microposts picture:string class AddPictureToMicroposts < ActiveRecord::Migration[5.1] def change add_column :microposts, :picture, :string end end
class Tag < ApplicationRecord validates :title, presence: true, uniqueness: { case_sensitive: false } has_many :taggings, dependent: :destroy has_many :posts, through: :taggings, source: :taggable, source_type: 'Post' has_many :images, through: :taggings, source: :taggable, source_type: 'Image' has_many :ev...
class VoteMailer < ActionMailer::Base default from: "notifications@acrofriends.com" def voting_email(info) @gamedataemail = info @game = Game.find(@gamedataemail.game_id) @user = User.find(@gamedataemail.user_id) mail(to: @user.email, from: "notifications@AcroFriends.com", subject: 'AcroFrie...
module Providers class Betcity < Base module Tennis def parse(page) page.search('//table/thead').each do |league_node| parent_node = league_node.parent league_identifier = league_node.at('a')[:name].gsub(/[^\d]/, '') sport_name, league_name = league_node.content.split...
require 'spec_helper' aws_cli_version = '1.7.26' describe RSpec.configuration.docker_image_name do describe file('/usr/bin/aws') do it { is_expected.to be_executable } end describe command('/usr/bin/aws --version') do its(:stderr) { is_expected.to include("aws-cli/#{aws_cli_version}") } end end
require 'rspec' class Money attr_reader :amount, :currency def initialize(amount, currency) @amount = amount @currency = currency end def times(mult) self.class.new(amount * mult, currency) end def equal?(money) return false if money.nil? @amount == money.amount && currency == money...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # before_action :find_user before_action :lookup_user def render_404 # DPR: supposedly this will actually render a 404 page in production raise ActionController::RoutingError.new('Not Found') end private # ...
FactoryBot.define do factory :transaction do invoice credit_card_number { Faker::Number.between(1, 200000) } # credit_card_expiration_date { Faker::Number.between(1, 100000) } result { ["Failed", "Success"].sample } end end
# frozen_string_literal: true require 'application_system_test_case' module Profile class UpdateTest < ApplicationSystemTestCase test 'guest user cannot access to profile' do visit profile_path assert_content 'You need to sign in or sign up before continuing.' assert_current_path new_teacher_s...
class Task < ApplicationRecord validates :description, length: { minimum: 2 } end
require 'spec_helper' describe "UrlHelper" do before do Plek.any_instance.stub(:website_root).and_return('http://test.gov.uk') @schemes = [].tap do |ary| 45.times { |n| ary << :"scheme#{n+1}" } end end it "should provide next and previous pagination links" do results = Pagination::Paginat...
class Route < ActiveRecord::Base has_many :trips, :inverse_of => :route, :dependent => :destroy validates :number, presence: true, uniqueness: true, format: { with: /\A[0-9]{3,4}\-?\w?\z/ } validates :name, presence: true, uniqueness: true, length: { in: 3..50 }, format: { with: /\A.+\s\/\s.+\z/ } def full_na...
class DirectorsController < ApplicationController def show id = params[:id] @movie = Movie.find(id) @director = @movie.director if @director == nil || @director == '' flash[:notice] = "'#{@movie.title}' has no director info" redirect_to "/movies" and return end @results = Movie.w...
get '/' do # La siguiente linea hace render de la vista # que esta en app/views/index.erb erb :index end get '/register' do erb :register end post '/register' do username = params[:username] password = params[:password] user = User.find_by(username: username) if user return "Name already taken" ...
class AddFixedAndHourlyToLineItems < ActiveRecord::Migration def change add_column :line_items, :hours_qty, :integer add_column :line_items, :hours_rate, :decimal add_column :line_items, :fixed_qty, :integer add_column :line_items, :fixed_rate, :decimal add_column :line_items, :price_type, :string...
require 'test_helper' require 'google/protobuf' require 'protip/decorator' require 'protip/resource' require 'protip/transformer' describe Protip::Decorator do let(:transformer) do Class.new do include Protip::Transformer end.new end let(:pool) do pool = Google::Protobuf::DescriptorPool.new...
class TCPSocket KILL_SIGNAL = 'KEEP ALIVE?' def keep_alive? begin return self.write(TCPSocket::KILL_SIGNAL) && self.flush rescue Errno::EPIPE return false end end end def send_policy_file(sock) policy = <<-POL <?xml version="1.0" encoding="UTF-8"?> <cross-domain-pol...
# frozen_string_literal: true module DefraRuby module Alert class Configuration attr_accessor :root_directory, :logger, :environment, :host, :project_key, :blocklist, :enabled def initialize @blocklist = [] @enabled = false end end end end
class User < ActiveRecord::Base has_secure_password validates :username, presence: true, uniqueness:true has_many :books, foreign_key: "user_id" end
# frozen_string_literal: true module Account class User < ApplicationRecord self.table_name = 'users' devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable scope :active, -> { where(active: true) } end end
class PlotPlant < ApplicationRecord belongs_to :plot belongs_to :plant has_many :gardens, through: :plot end
class CreateMatches < ActiveRecord::Migration[5.2] def change create_table :matches do |t| t.belongs_to :static, null: false t.belongs_to :retailer, null: false t.belongs_to :users t.integer :suggested_static_id t.boolean :approved t.datetime :suggested_on t.float :manufac...
# Workaround to make Rubygems believe it builds a native gem require 'mkmf' create_makefile('none') # TODO: determine whether we really need to be working around instead of with mkmf if `uname -s`.chomp != 'Darwin' puts "Warning! Only Darwin (Mac OS X) systems are supported, nothing will be compiled" else begin ...
=begin #=============================================================================== Title: Scene Interpreter Author: Hime Date: Nov 21, 2015 -------------------------------------------------------------------------------- ** Change log Nov 21, 2015 - fixed bug where item menu crashes when using common event...
class Bioentry < ActiveRecord::Base belongs_to :biodatabase has_one :bioentry_record has_many :dbxrefs has_many :lcmsresults has_many :goassignments has_many :peptide_genomedb_results def self.lcms_page(cond, includetables, page) basecond = "bioentries.biodatabase_id = 2 and bioentries.accession lik...
require_relative "../lib/fraction_reductions.rb" require "benchmark" describe FractionReductions do context "#naive" do it "should get the right answer for 12" do FractionReductions::naive(12).should == 8 end end context "#by_factors" do it "should get the right answer for 12" do Fracti...
class AddPublicToRecommendations < ActiveRecord::Migration def change add_column :recommendations, :public, :boolean, :default => false add_column :recommendations, :url, :string end end
class Admin::SongsController < Admin::ApplicationController before_action :set_song, only: [:edit, :update, :destroy] def new @song = Song.new end def create @song = Song.new(song_params) if @song.save flash[:success] = "You have successfully added #{@song.name} to the Repertoire." re...
class CollectionsNameUniquenessValidator < ActiveModel::Validator # def validate_each(record, attribute, value) # record.errors[attribute] << "Collections names must be unique" unless value.map(&:name).uniq.size == value.size # end end
class StripeEventHandler def self.charge_failed_for_customer(customer, event) if failed_user = User.find_by(customer_id: customer) failed_user.update(active: false) StripeEventMailer.failed_payment_notification(failed_user.id).deliver_now Rails.logger.info "StripeEvent | Failed payment notifica...
class RemovePurchaseDateColumnToProduct < ActiveRecord::Migration[5.2] def up remove_column :products, :purchase_date, :date end def down add_column :products, :purchase_date, :date end end
class NoneTemplate PERKS = { } def apply_perks return PERKS end def name return 'no weapon' end end
class AddExternalServiceIdToExportedFiles < ActiveRecord::Migration[5.2] def change add_reference :exported_files, :external_system, foreign_key: true end end
# ================================================================================ # Part: BALANCE SYSTEM # Desc: # Place all transaction receipt here (payment confirm, etc) # ================================================================================ class PaymentConfirmation include Mongoid::Document include...
require 'oauth/signature/base' require 'openssl' module OAuth::Signature::RSA class SHA1 < OAuth::Signature::Base implements 'rsa-sha1' def ==(cmp_signature) public_key = OpenSSL::PKey::RSA.new(request.consumer.secret) public_key.verify(OpenSSL::Digest::SHA1.new, cmp_signature, signature_base_st...
require 'spec_helper' describe SpyFu::Requests::LeadsApi do subject { SpyFu::Requests::LeadsApi } describe '#get_contact_card' do it 'fails without domain' do expect { subject.get_contact_card({}) }.to raise_error SpyFu::Errors::MissingRequireParameters end it 'calls SypFu::Request' do ex...
# frozen_string_literal: true require 'sauce_bindings' require 'rspec' describe 'Basic Options' do before { WebMock.allow_net_connect! } it 'creates session' do # 1. Create a SauceOptions instance with the 3 primary parameters sauce_options = SauceBindings::Options.new(browser_name: 'firefox', ...
class AddRefereeIdToMatches < ActiveRecord::Migration[5.1] def change add_column :matches, :referee_id, :integer end end
require 'spec_helper' describe 'Granule metadata' do before do load_page :search fill_in 'keywords', with: 'C179003030-ORNL_DAAC' wait_for_xhr first_collection_result.click # Select a specific granule click_link 'Filter granules' fill_in 'granule_id', with: 'FIFE_STRM_15M.80611715.s15' ...
class TestBase < ActiveRecord::Migration def up create_table :test_suites do |t| t.string :title, :null => false t.belongs_to :user, :null => false t.timestamps end create_table :test_cases do |t| t.string :title, :null => false t.text :description t.text :steps ...
class AddStateToGgKeywords < ActiveRecord::Migration def change add_column :gg_keywords, :state, :string end end
class Quarter < ApplicationRecord has_many :lunches, dependent: :nullify class << self def current_quarter find_or_create_quarter(Date.current) end def find_or_create_quarter(date) quarter = Quarter.where('start_date <= ?', date).find_by('end_date >= ?', date) quarter = QuarterCreate...
class ContactsController < ApplicationController before_filter :require_current_user! def create @contact = Contact.new(params[:contact]) if @contact.to @contact.create_mailbox_etc if @contact.pair_exists? else respond_to do |format| format.json { render json: { error: "no such use...
# -*- encoding : utf-8 -*- require 'rails_helper' RSpec.describe OpenSAPCourseWorker do let!(:mooc_provider) { FactoryGirl.create(:mooc_provider, name: 'openSAP') } let(:open_sap_course_worker) { described_class.new } it 'delivers MOOCProvider' do expect(open_sap_course_worker.mooc_provider).to eql mooc_pr...
# frozen-string-literal: true require File.join(File.dirname(__FILE__), 'helper') class TestID3v1Tag < Test::Unit::TestCase context 'The id3v1.mp3 file' do setup do read_properties = false @file = TagLib::MPEG::File.new('test/data/id3v1.mp3', read_properties) end should 'have an ID3v1 tag' ...
# # Be sure to run `pod lib lint JeweledKit.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'JeweledK...
class Student < ActiveRecord::Base # Include default devise modules. Others available are: # , :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable has_many :registrations has_many :courses, thro...