text
stringlengths
10
2.61M
require 'tty-prompt' require 'artii' class Game < ActiveRecord::Base attr_reader :our_team_id has_many :finishing_positions @our_team_id = nil # CONTROL FLOW FUNCTIONS def wait_for_any_key require 'io/console' puts ' ' puts 'Press any key to continue' puts '' STDIN.getch end def ...
# frozen_string_literal: true require 'rails_helper' describe 'teachers', type: :request do let(:headers) do { 'Accept' => 'application/vnd.api+json', 'Content-Type' => 'application/vnd.api+json' } end let(:params) { { teacher: teacher }.to_json } subject do request! response e...
describe "Command" do before(:each) do @game = Game.new end context "PLACE command" do it "Report command: Unplace robot" do expect do result = @game.execute_command("REPORT") expect(result).to eq(true) end.to output(/Unplaced/).to_stdout end it "Place command: wron...
class PapersController < ApplicationController def index if params[:year].nil? == false @papers = Paper.published_in(params[:year]) else @papers = Paper.all end end def show @paper = Paper.find(params[:id]) end def new @paper = Paper.new end def edit @paper = Paper.find(params[:id]) end d...
require 'rails_helper' describe ResourceAssetPolicy do subject { ResourceAssetPolicy.new(user, resource_asset) } context 'visitante não pode ver material do participante' do let(:user) { nil } let(:resource_asset) { create(:asset_event_participant_material) } it { should_not permit(:show) } ...
=begin puts 1 + 1 This is a multiline comment section. They are not used as often as just including a # at the beginning of every line. =end puts "Multi line comments in the section above."
module MixpanelTest class Analysis def initialize(options = {}) @events_count = {} @events_properties_counts = {} @events_properties_values_counts = {} @properties_counts = {} @properties_values_counts = {} @super_properties_counts = {} @super_properties_values_counts ...
# == Schema Information # # Table name: customers # # id :integer not null, primary key # name :string(255) # description :text(65535) # created_at :datetime not null # updated_at :datetime not null # phone :string(255) # qq_number :string(255) # class Customer...
class AddVideoToVirtualTourisms < ActiveRecord::Migration def change add_attachment :virtual_tourisms, :video end end
require 'redmine' Redmine::Plugin.register :redmine_graph_activities do name 'Redmine Graph Activities plugin' author '@me_umacha' description "The plugin to generate a graph for visualizing members' activities." version '0.0.3' # This plugin works as a project module and can be enabled/disabled at project ...
module Moped class Indexes include Enumerable private def database @database end def collection_name @collection_name end def namespace @namespace end def initialize(database, collection_name) @database = database @collection_name = collection_nam...
module SuckerPunch class << self attr_accessor :queues def reset! self.queues = {} end end SuckerPunch.reset! class Queue attr_reader :name def initialize(name) @name = name SuckerPunch.queues[name] ||= [] end def self.[](name) new(name) end def ...
p 10 != 5 # true p 10 != 10 # false puts p "Hello" != "Goodbye" # true p "Hello" != "Hello" # false p "Hello" != "hello" # true (not the same case) puts # good to settle on a common method like .downcase capital_hello = "HeLLo" lower_hello = "hello" p capital_hello == lower_hello p capital_hello.downcase == lower_he...
class CreatePosts < ActiveRecord::Migration def self.up create_table :posts, :force => true do |t| t.integer :user_id t.string :content,:limit=>210 t.string :logo,:limit=>50 t.integer :forward_posts_count,:default=>0 t.integer :favorite_posts_count,:default=>0 t.boolean :is_hi...
class State < FlactiveRecord::Base end class Programmer < FlactiveRecord::Base end describe "Metaprogrammed Amazingness" do DBConnection.instance.dbname = 'dynamic_orm_test' CONN = DBConnection.instance.connection context "superclass" do it "exists" do expect{FlactiveRecord::Base}.to_not raise_error...
class UsersController < ApplicationController skip_before_action :verify_authenticity_token before_action :require_user, only: [:show] before_action :require_admin, only: [:index, :destroy] def index @trainer = User.find_by(id: 1) @users = User.where(admin: false) end def show @trainer = User....
require "rails_helper" RSpec.describe BulkApiImport::FhirObservationImporter do before { create(:facility) } let(:import_user) { ImportUser.find_or_create } let(:facility) { import_user.facility } let(:facility_identifier) do create(:facility_business_identifier, facility: facility, identifier_type: :exter...
module Fastlane module Actions # Adds a git tag to the current commit class EmailApnsCertsAction < Action def self.run(options) end def self.description "This will email all the APNS Push Certs to Backend" end def self.available_options [ Fast...
class TranslateMultipleForm include ActiveModel::Model FIELDS = %i[column_name from_locale to_locale].freeze attr_accessor :records, *FIELDS attr_reader :message validates(*FIELDS, presence: true) def save # rubocop:todo Metrics/MethodLength already_exists = 0 blank_source = 0 successfully_tr...
require 'meta-spotify' # meta-spotify gem: Ruby wrapper for the spotify API require_relative 'ArtistSearch' require_relative 'AlbumsByArtistSearch' class Game def initialize @artist_search_term = nil @artist_search_result = nil @artist_index = nil @album_search_result = nil @album_index = nil @is_running...
=begin We are going to create a BankAccount class. This class will recreate some of the common account transactions that normally occur for a bank account such as displaying your account number, checking and savings amount, total amount. Of course, there are also methods to invoke such as depositing a check, checking y...
require 'test_helper' class PhoneVerificationsControllerTest < ActionController::TestCase setup do @phone_verification = phone_verifications(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:phone_verifications) end test "should get new" do ...
class LikesController < ApplicationController before_action :authenticate_user! before_action :find_picture def create @like = current_user.likes.create!(like_params) end def destroy Like.find(params[:id]).destroy end private def like_params params.permit(:picture_id) end def find_p...
class SessionsController < ApplicationController # GET login form def new end # POST create new def create @user = User.find_by(email: params[:session][:email].downcase) # because we're working with the Session resource, the params hash has a [:session] key that holds our form data if @user && @user...
require('spec_helper') describe(Company) do describe(".all") do it("starts with an empty array of stops") do expect(Company.all()).to(eq([])) end end # describe(".find_category_expenses") do # it("return a list of expenses for a category") do # test_category = Category.new({:name => "Bi...
require 'spec_helper' describe Visualization::Boxplot, :database_integration => true do let(:account) { GpdbIntegration.real_gpdb_account } let(:database) { GpdbDatabase.find_by_name_and_gpdb_instance_id(GpdbIntegration.database_name, GpdbIntegration.real_gpdb_instance) } let(:dataset) { database.find_dataset_in...
class CreateStats < ActiveRecord::Migration def change create_table :stats do |t| t.string :surname, null: false t.string :given_name, null: false t.string :position, null: false t.string :league, null: false t.string :division, null: false t.string :team_name, null: false ...
class User < ActiveRecord::Base has_and_belongs_to_many :permissions acts_as_authentic :logged_in_timeout => 60.minutes, :password_field_validates_presence_of_options => { :on => :update, :if => :update_password? } attr_accessor :dont_update_password def current_or_last_ip current_login_ip || last_log...
module Rockauth class MigrationsGenerator < Rails::Generators::Base def install_migrations Dir[File.expand_path("../../../../db/migrate/*.rb", __FILE__)].each do |file| copy_file file, "db/migrate/#{File.basename(file)}" end end end end
require 'rails_helper' require 'platforms/yammer/client' module Platforms module Yammer RSpec.shared_examples "API module" do |mod| let(:klass) { Api.const_get(mod.camelize) } it { expect(client.send(mod)).to be_a klass } describe "constructor" do before(:each) do allow(klas...
class BackgroundsController < ApplicationController def index list render("list") end def list @backgrounds = Background.all end def show @background = Background.find(params[:id]) end def new @background = Background.new end def create @background = Background.new(b...
require 'codily/elements/service_belongging_base' module Codily module Elements class Condition < ServiceBelonggingBase def_attr *%i( comment priority statement ) def setup delete_if_empty! *%i( comment ) force_integer! *%i( p...
require 'rails_helper' RSpec.describe 'タスク管理機能', type: :system do let!(:basic_user) { FactoryBot.create(:basic_user) } let!(:task) { FactoryBot.create(:task, user:basic_user) } let!(:second_task) { FactoryBot.create(:second_task, user: basic_user) } before do visit new_session_path fill_in 'session[emai...
require "administrate/base_dashboard" class BarcodeDashboard < Administrate::BaseDashboard # ATTRIBUTE_TYPES # a hash that describes the type of each of the model's fields. # # Each different type represents an Administrate::Field object, # which determines how the attribute is displayed # on pages through...
# Write a Producer thread and a Consumer thread that share a fixed-size buffer # and an index to access the buffer. The Producer should place numbers into the # buffer, while the Consumer should remove the numbers. The order in which the # numbers are added or removed is not important. class IntBuffer require 'th...
class Tekka < Formula desc "Individual-based simulator of pacific bluefin tuna" homepage "https://github.com/heavywatal/tekka" url "https://github.com/heavywatal/tekka/archive/v0.7.1.tar.gz" sha256 "cba04ddd16815ac653a875e1153429d9fce43cd73b1ffbde263bdee9ceb5be28" head "https://github.com/heavywatal/tekka.git...
namespace :db do desc "Load default contacts for users" task :analyze => :environment do puts '' puts 'Running database analysis task...' puts "\tThis task will scan the database for errors and log them to a file" load_user_default_emails end end # See if this user ha...
class Article < ApplicationRecord include PermissionsConcern has_many :has_categories, dependent: :delete_all has_many :categories, through: :has_categories has_many :comments after_create :categories belongs_to :user validates :title, uniqueness: true validates :title, :body, presence: true #valida...
namespace :db do desc "Fill database with sample data" task populate: :environment do make_users make_microposts make_relationships make_subjects make_topics make_grades make_user_groups make_items #make_sub_items make_test_sheets make_schedule end end def make_users admin = User.create!(name...
class Puppy def initialize puts "Initializing new puppy instance..." end def fetch(toy) puts "I brought back the #{toy}!" toy end def speak(number_of_barks) i = 0 while i < number_of_barks puts "woof" i += 1 end end def roll_over puts "roll over" end def dog_years...
# frozen_string_literal: true class CreateChallenges < ActiveRecord::Migration[5.1] def change create_table :challenges do |t| t.belongs_to :record_book, null: false t.string :name, null: false t.integer :challenge_type, null: false t.boolean :repeatable, default: false, null: f...
begin_registration_time = Time.parse '2012-09-10 11:13:02 UTC' Fabricator(:voter) do # legacy_id is a eight hex symbols legacy_id { (rand(16 ** 8) + (16 * 7 + 1)).to_s(16) } registered_at do sequence(:registered_at) { |i| begin_registration_time + i.minutes } end phone_number { '...' + rand(999).to_s } ...
describe IGMarkets::PayloadFormatter do class PayloadModel < IGMarkets::Model attribute :the_string attribute :the_symbol, Symbol, allowed_values: [:two_three] attribute :the_date, DateTime, format: '%Y/%m/%d' end it 'formats payloads correctly' do model = PayloadModel.new the_string: 'string', t...
require 'spec_helper' # Tests for RobotView describe RobotView do # Create a new instance for each test before :each do @view = RobotView.new end # Test initialize describe "#new" do it "is an instance of RobotView" do expect(@view).to be_an_instance_of(RobotView) end end # Test disp...
class GlobalTemplatesQuery < Types::BaseResolver description "Gets all the global templates" type Outputs::TemplateType.connection_type, null: false policy ApplicationPolicy, :logged_in? def authorized_resolve Template.global end end
class LocationHelper # merge the specified set of locations, keeping the first location in the collection def self.merge_locations(locations) return nil if locations.blank? return locations.first if locations.size == 1 location = locations.delete_at(0) company = location.company ...
class Chapter < ApplicationRecord belongs_to :user belongs_to :learning has_one_attached :video end
# frozen_string_literal: true require 'stannum/contracts/parameters_contract' require 'support/examples/constraint_examples' require 'support/examples/contract_builder_examples' require 'support/examples/contract_examples' RSpec.describe Stannum::Contracts::ParametersContract do include Spec::Support::Examples::Co...
# A line of people at an amusement park ride # There is a front to the line, as well as a back. # People may leave the line whenever they see fit and those behind them take their place. class Line attr_accessor :members attr_accessor :front, :back, :middle def initialize self.members = [] end def join(p...
class AddYearIndexToPopulations < ActiveRecord::Migration[5.2] def change add_index :populations, :year end end
require 'sorting_strategy' require 'binary_heap' class HeapSort # Important Characteristics # 1. One of the best sorting methods being in-place and with no quadratic worst-case scenarios # 2. Involves two basic parts: # - Creating a Heap of the unsorted list # - Then a sorted array is created by repeate...
# frozen_string_literal: true require_relative 'transaction' require_relative 'transaction_history' require_relative 'bank_statement' class BankAccount def initialize(transaction_history = TransactionHistory.new, bank_statement = BankStatement.new) @balance = 0.00 @transaction_history = transaction_histor...
require('minitest/rg') require('minitest/autorun') require_relative('./sports_team') class TestSportsTeam < MiniTest::Test def setup @edinburgh = SportsTeam.new("Edinburgh Rugby", ["Grieg", "Jo"], "Vern") end def test_update_coach @edinburgh.update_coach("Jimmy") assert_equal("Jimmy", @edinburgh....
class CovidCase::Scraper def self.scrape_states doc = Nokogiri::HTML(open("https://coronavirus.jhu.edu/region")) states = doc.css("div.RegionMenu_items__3D_d2 a.Button_base__2nEBG.Button_style-filled-light__14tVT.Button_shape-square__31KW9.has-icon.null") states.collect do |state| ...
module Decogator module Decoration module ClassMethods [:before, :around, :after, :tap].each do |advice| module_eval <<-EOS def #{advice}(*args, &block) __process_advice__(#{advice.inspect}, *args, &block) end EOS end def __process_advice__(...
class CommentsController < ApplicationController def create @commentable = find_commentable @comment = @commentable.comments.new(comment_params) if @comment.save redirect_to :back else flash[:errors] = @comment.errors.full_messages redirect_to :back end end def find_com...
class Changestatustenantstostring < ActiveRecord::Migration def change remove_column :tenants, :status, :boolean add_column :tenants, :status, :string end end
require 'faker' FactoryGirl.define do sec = Faker::Number.number(5) factory :timer do title { Faker::Lorem.word } kind { Timer.kind.values.sample } active { [true, false].sample } amount { sec } start_at { Time.zone.now } end_at { Time.zone.now + sec.to_i.seconds } association :user, ...
module ReverseMarkdown class Mapper attr_accessor :raise_errors attr_accessor :log_enabled, :log_level attr_accessor :li_counter attr_accessor :github_style_code_blocks def initialize(opts={}) self.log_level = :info self.log_enabled = true self.li_counter = 0 self.githu...
# http://www.mudynamics.com # http://labs.mudynamics.com # http://www.pcapr.net require 'find' require 'set' require 'fileutils' require 'tempfile' require 'digest/md5' module PcaprLocal class Scanner # Creates scanner instance and starts it. def self.start config scanner = Scanner.new config ...
Puppet::Type.type(:service).provide :service do desc "The simplest form of service support." def self.instances [] end # How to restart the process. # If the 'configvalidator' is passed, it will be executed and if the exit return # is different than 0, preventing the service to be stopped from a stabl...
require 'json' module ExceptionHub class Notifier def perform(exception, env) @exception = exception @env = env self.notify! self end def notify! begin issue = Issue.new issue.description = build_description(@exception, @env) issue.title = "#{@except...
Rails.application.routes.draw do resources :appellations resources :wines resources :varietals resources :producers resources :countries # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class ImagesController < InheritedResources::Base private def image_params params.require(:image).permit(:title, :description, :picture) end end
require 'spec_helper' describe 'Students' do before :each do DB.execute("CREATE TABLE students (id INTEGER PRIMARY KEY AUTOINCREMENT, student TEXT)") end after :each do DB.execute("DROP TABLE students") end end describe '#name' do it "has a name" do s = Students.new s.name = "Peter" ...
module EmailValidatorSpec class User include ActiveModel::Validations attr_accessor :email validates :email, presence: true, email: true end end RSpec.describe MailgunEmailValidator do before(:all) do ActiveRecord::Schema.define(version: 1) do create_table :email_validator_spec_users, forc...
# # Cookbook Name:: pypy # Recipe:: default # # Copyright 2013, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # def install_pypy(source, file, build_dir, prefix) remote_file "#{Chef::Config[:file_cache_path]}/#{file}" do source source + file mode '0644' action :create_if_missing not_...
class ApplicationController < ActionController::Base include Oauth2Provider::ControllerMixin protect_from_forgery helper_method :current_user_session, :current_user before_filter :require_user private def current_user_session return @current_user_session if defined?(@current_user_session) @current...
module Taobao class PromotionDetail def self.attr_names [:id, :promotion_name, :discount_fee, :gift_item_name, :gift_item_id, :gift_item_num, :promotion_desc, :promotion_id] end attr_names.each do |attr_name| attr_accessor attr_name end end end
require 'spec_helper' describe DatasetStreamer, :database_integration => true do let(:database) { GpdbDatabase.find_by_name_and_gpdb_instance_id(GpdbIntegration.database_name, GpdbIntegration.real_gpdb_instance) } let(:dataset) { database.find_dataset_in_schema("base_table1", "test_schema") } let(:user) { GpdbIn...
require File.dirname(__FILE__) + '/spec_helper' require 'active_model' require 'active_model/core' ActiveModel::Base.send :include, ObserverDisabler class ObservedModel < ActiveModel::Base class Observer end end class FooObserver < JitObserver class << self public :new end attr_accessor :stub de...
module PlayerStatistics ## # Statistic that computes how many matches a given [Player](#Player) has participated in. class MatchesPlayedStatistic < PlayerStatistics::PlayerStatistic def compute query = Match .joins('JOIN match_teams_players ON match_teams_players.match_team_id IN (matches.red_te...
require 'spec_helper' describe "static pages" do describe "home page" do subject {page} before {visit root_path} #测试标题 it {should have_title("主页")} #测试内容 it {should have_content("国科大跳蚤市场")} it {should have_content("主页")} it {should have_content("注册")} it...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'telegram/rabbit/version' Gem::Specification.new do |spec| spec.name = "telegram-rabbit" spec.version = Telegram::Rabbit::VERSION spec.authors = ["Stanislav E. Govorov"...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html # get '/documents' => "documents#my_index" root "documents#index" resources :documents end
class CategorySalesPlan < ApplicationRecord extend CommercialCalendar::Period belongs_to :store belongs_to :category, foreign_key: 'category_cod' scope :by_store_month, ->(store_id, opts = {}) { where(store_id: store_id, year: opts[:year], month: opts[:month]) } scope :between, ->(period, store_id) { ...
log 'Started execution custom nuget.exe downloader' do level :info end temp_dir ='C:\\Users\\vagrant\\AppData\\Local\\Temp' scripts_dir = temp_dir.gsub('\\','/') system = node['kernel']['machine'] == 'x86_64' ? 'win64' : 'win32' download_url = node['custom_nuget']['download_url'] filename = node['custom_nuget']['fil...
class ApplicationController < ActionController::Base include PublicActivity::StoreController include Pundit include Devise::Controllers::Helpers # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. # protect_from_forgery with: :exception # protect_from_fo...
class AddColumnDate < ActiveRecord::Migration[5.0] def change add_column :orcamentos, :data, :date end end
require_relative 'clients' require_relative 'collect' require 'twitter' class Menu attr_accessor :input2, :collect def initialize @collect = Collect.new end def start_menu system 'clear' puts "" puts " ::::::::::::::::::::::::" puts " : Twitter_bot, Welcome :" puts " ::::::::::::::::::::::...
require 'NumeroRacional.rb' require 'test/unit' class Testeo < Test::Unit::TestCase def setup #Crea un obejeto Racional como atributo de la clase Testeo. @nr = Racional.new(1,2) end def test_objeto #Determina si los tipos son correctos y si la función to_s funciona. assert_instance_of(String,@nr.to_s,"No es u...
module Roadie::Rails::InlineOnDelivery def deliver_now inline_styles super end end class ApplicationMailer < ActionMailer::Base include Roadie::Rails::Automatic before_action :attach_header_image ADMIN_ADDRESS = 'admin@tutoria.io' default from: 'no-reply@tutoria.io' layout 'mailer' def road...
require_relative "board" require_relative "cursor" class Game def initialize(grid_size, mine_count) @board = Board.new(grid_size, mine_count) @cursor = Cursor.new(grid_size) end def make_move(command, pos) case command when "flag" @board.toggle_flag(pos) when "reveal" @board.reve...
class ApplicationController < ActionController::Base before_filter :set_time_zone def ensure_sign_in if current_user.nil? redirect_to index_user_omniauth_authorize_path return false end end def set_time_zone Time.zone = 'Tokyo' end end
# frozen_string_literal: true require 'set' require 'stannum' module Stannum # An errors object represents a collection of errors. # # Most of the time, an end user will not be creating an Errors object # directly. Instead, an errors object may be returned by a process that # validates or coerces data to a...
class AddUserIdToJobColumn < ActiveRecord::Migration def change add_column :job_columns, :user_id, :integer end end
class CandidateRevision < ActiveRecord::Base belongs_to :candidate belongs_to :revision end
require 'test_helper' class FriendTest < ActiveSupport::TestCase test 'requires name' do friend = Friend.new refute_predicate friend, :valid? assert_includes friend.errors.messages[:name], "can't be blank" end test 'validates name length' do name = 'a' * (Friend::MAX_NAME_LENGTH + 1) friend...
class MasterMind attr_accessor :input, :output, :gameEngine def initialize(input, output, gameEngine) @input = input; @output = output; @gameEngine = gameEngine; end def run() num = 0; combination = gameEngine.getCombination(); answer = ""; while(!gameEngine.match(combination, answer) && !gameEngine...
class AddPayStructureToEmployees < ActiveRecord::Migration def change add_column :employees, :pay_type, :string add_column :employees, :pay_rate, :decimal, :precision => 8, :scale => 2 end end
# frozen_string_literal: true # == Schema Information # # Table name: roles # # id :integer not null, primary key # name :string # resource_type :string # created_at :datetime not null # updated_at :datetime not null # resource_id :integer # # Indexes # # ind...
require_relative '../../config/application' class Controller HELP_MENU = <<EOF HELP MENU Type: add <task description> add a task to the end of the list remove <task id> delete a task complete <task id> complete a task list show all tasks save <file_name> save the list to a ...
class MessagesController < ApplicationController def index @messages = Message.all end def show @message = Message.find(params[:id]) end def new @message = Message.new(message_params) end def create @message = Message.create(message_params) respond_to do |format| format.html...
require 'httparty' class EpaApi include HTTParty base_uri('https://iaspub.epa.gov') def initialize(zipcode) @response = self.class.get("/enviro/efservice/getEnvirofactsUVHOURLY/ZIP/#{zipcode}/json") end def hourly @response.parsed_response end end
class Author attr_accessor :name def initialize(name) @name = name @posts = [] end def posts @posts end def add_post(one_post) @posts << one_post one_post.author = self end def add_post_by_title(post_title) one_post = Post.new(post_title) @posts << one_po...
Rails.application.routes.draw do get "/" => "tasks#home" end
module Common def initialize super() end def get_check_last_runtime(client, check) request = RestClient::Resource.new( "#{config[:sensu_scheme]}://#{config[:sensu_api]}:#{config[:sensu_port]}/#{client}/#{check}", timeout: config[:sensu_timeout], user: config[:sensu_user], passwor...
class ReviewsController < ApplicationController def create @product = Product.find(params[:product_id]) @review = @product.reviews.create(review_params) redirect_to product_path(@product) end private def review_params params.require(:review).permit(:reviewer, :review_title, :review) end end
class Login def initialize(params) @params = params end def call user = User.find_by(email: @params['email']).try(:authenticate, @params['password']) token = user ? user.generate_access_token : nil if token.nil? Error.new(I18n.t('api.login_fail')) else Success.new(token) end ...
module LtreeRails module HasLtree extend ActiveSupport::Concern module ClassMethods def has_ltree(opt = {}) include_dependencies check_options!(opt) apply_options(opt) end alias_method :act_as_ltree, :has_ltree private def include_dependencies ...