text
stringlengths
10
2.61M
class AddCanTextToStudent < ActiveRecord::Migration def change add_column :students, :can_text, :boolean, :default => true end end
module PivotalAngel class Label class << self def apply_to(stories, label) stories.each do |s| story = get_story(s) labels = story.labels.split(',') labels << label unless labels.include?(label) story.update(:labels => labels.join(',')) end en...
# Problem 69: Totient maximum # http://projecteuler.net/problem=69 # # Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, ...
require 'spec_helper' describe RatingsController do render_views login_user describe "PUT 'update'" do before(:each) do @rating = Factory(:rating, :user => @user) end describe "success" do before(:each) do @attr = { :user_id => @user.id, :beer_id ...
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 module TwitterCldr module Transforms module Conversions class ConversionRule < Rule class << self include TwitterCldr::Tokenizers def parse(rule_text, symbol_table, index) ...
require 'faraday' require 'faraday_middleware' require 'faraday-request-timer' class BuyBack attr_accessor :status def initialize(response) @response = response @offers, @top_offer, @asin = set_data if @response.success? @status = @response.status @requestor = @response.env.request.proxy.uri.to_s....
class AddXGridToImage < ActiveRecord::Migration[5.2] def change add_column :images, :x_grid, :integer add_column :images, :y_in_lines, :integer add_column :images, :height_in_lines, :integer add_column :images, :detail_mode, :boolean add_column :images, :draw_frame, :boolean, default: true add...
class FontMohave < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/mohave" desc "Mohave" homepage "https://fonts.google.com/specimen/Mohave" def install (share/"fonts").install "Mohave-Italic[wght].ttf" (share/"fonts").install "Moh...
class MedusaIngest < ActiveRecord::Base def self.incoming_queue IDB_CONFIG['medusa']['incoming_queue'] end def self.outgoing_queue IDB_CONFIG['medusa']['outgoing_queue'] end def self.on_medusa_message (response) response_hash = JSON.parse(response) if response_hash.has_key? 'status' #...
# frozen_string_literal: true class OrderAppender include DateHelper attr_reader :original_order, :user def initialize(original_order, user) @original_order = original_order @user = user end def add!(product, quantity, params) OrderDetail.transaction do products = product.is_a?(Bundle) ...
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string # encrypted_password :string not null # roles :string is an Array # reset_password_token :string # reset_password_sent_at :da...
require_relative 'SystemStrings' require_relative './Command/UserCommand/Abstract/StorageCommand' require_relative './Command/UserCommand/Abstract/RetrievalCommand' require_relative './Command/UserCommand/Abstract/ServerCommand' class CommandValidator def initialize(commands) @command_hash = commands @com...
require 'rspec' require 'pry' require 'word' describe(Word) do before() do Word.clear end describe('.all') do it('will display dictionary as empty array') do expect(Word.all).to(eq([])) end end describe('#initialize') do it('create a new word') do new_word = Word.new({:word=> '...
require_relative "../Modules" require_relative "../Piece" class King < Piece attr_reader :symbol, :color include Stepable def initialize(name, start_pos, color, board) super(name, start_pos, color, board) @symbol = :Z @color = color end def move_dirs return [ [1, 1], [-1, -1], ...
class ProjectBuilder include Transactable include Virtus.model # Project attribute :title, String attribute :description, String # Todo List attribute :todo_list_title, String, default: "Sample Todo List" attribute :todo_list_description, String, default: "New Todos" # Todo attribute :todo_title,...
set :stage_dir, 'app/config/deploy' # needed for Symfony2 only require 'capistrano/ext/multistage' set :stages, %w(production) set :repository, "git@github.com:janimattiellonen/website.git" set :scm, :git #set :keep_releases, 3 set :application, "Janimattiellonen-website" set :model_manager, "doctrine" ...
class AddCategoryToAccountingTransactions < ActiveRecord::Migration def change add_column :accounting_transactions, :category, :string end end
require 'bike' describe Bike do let(:bike) {Bike.new} it "is not broken when created" do expect(bike.broken?).to be false end it "should be broken" do bike.break! expect(bike.broken?).to be true end it "should be able to be fixed" do bike.break! bike.fix! expect(bike.broken?).to be false end ...
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "gravatar/version" Gem::Specification.new do |s| s.name = %q{gravatar-ultimate} s.version = Gravatar::VERSION s.authors = ["Colin MacKenzie IV"] s.date = %q{2010-08-30} s.description = %q{The Ultimate Gravatar Gem! This gem is u...
# lib/tasks/sample_data.rake namespace :db do desc 'Drop, create, migrate, seed and populate sample data' task prepare: [:drop, :create, :migrate, :seed, :populate_sample_data] do puts 'Ready to go!' end desc 'Populates the database with sample data' task populate_sample_data: :environment do Chapter...
require 'spec_helper' describe PdfTempura::Extensions::Hash::StringifyKeys do subject do { foo: true, bar: { blah: "abc" }, woo: [ 1, { blorgh: false } ] }.extend(described_class) end describe "#stringify_keys" do example do ...
module ApplicationHelper def title if (content_for :page_title).blank? "Journal" else content_for :page_title end end end
require 'spec_helper' describe 'Map Zooming', reset: false do before :all do page.driver.resize_window(1680, 1050) # Default capybara window size Capybara.reset_sessions! visit '/search' end after :all do page.driver.resize_window(1280, 1024) end # context 'when zooming with the mouse scrol...
require "application_system_test_case" class SubjectsTest < ApplicationSystemTestCase setup do @subject = subjects(:one) end test "visiting the index" do visit subjects_url assert_selector "h1", text: "Subjects" end test "creating a Subject" do visit subjects_url click_on "New Subject" ...
class SubdomainPresent def self.matches?(request) subdomains = ['www', 'admin', 'public'] request.subdomain.present? && !subdomains.include?(request.subdomain) end end class SubdomainBlank def self.matches?(request) subdomains = ['www', 'admin', 'public', 'reboschule'] request.subdomain.blank? ||...
describe Node do it "validates the node" do data = ["node_id", "name", "geo", "flags", "macs"] Node.new(*data).valid?.should.eql true end it "creates valid nodes" do json = BW::JSON.parse(NODES) node = Node.from_json(json).first node.node_id.should.eql "66:70:02:b5:d9:26" node.na...
class ApplicationController < ActionController::Base protect_from_forgery layout 'application' def authorized_user? !session[:flickr_auth_token].blank? end helper_method :authorized_user? end
class CreateBearsInstances < ActiveRecord::Migration[5.0] def change create_table :bears_instances do |t| t.string :name t.string :comment t.timestamps end add_index :bears_instances, :name, unique: true end end
class CreateFoods < ActiveRecord::Migration[5.0] def change create_table :foods do |t| t.string :name t.string :type t.integer :default_price, :default => 0 t.integer :restaurant_id t.boolean :status, :default => 1 t.float :average_star, :default => 5 t.string :descriptio...
class User < ActiveRecord::Base # Remember to create a migration! has_many :followers has_many :my_followers, through: :followers, source: :user validates :email, uniqueness: true validates :username, uniqueness: true has_many :people_i_follow, foreign_key: "follow_id", class_name: "Follower" has_man...
class Player < ApplicationRecord Player.order('total_points DESC') belongs_to :team has_many :matches has_many :player_matches def self.search(search) where("first_name LIKE ?", "%#{search}%") where("second_name LIKE ?", "%#{search}%") end end
class CreateTickets < ActiveRecord::Migration[5.2] def up execute <<-SQL CREATE TYPE ticket_type AS ENUM ('even', 'all_together', 'avoid_one'); SQL create_table :tickets do |t| t.references :event, foreign_key: true, null: false t.references :reservation, index: false t.integer :p...
module Susanoo module Accessibility class Button < Base def validate(doc) doc.xpath("//button").each do |node| invalid_chars = Susanoo::Filter::non_japanese_chars(node[:value]) if invalid_chars.present? error('E_7_1', node) end end @messages ...
require 'open-uri' class GameController < ApplicationController def game @grid = generate_grid(10) @start_time = Time.now.to_i end def score @attempt = params["attempt"] @enable = attempt_not_in_grid(@attempt, @grid) @start_time = params["start_time"].to_i @end_time = Time.now.to_i @...
Pod::Spec.new do |spec| spec.name = "iHash" spec.version = "0.0.2" spec.summary = "Lib that generates hash values" spec.description = <<-DESC A CocoaPods library that generates hash values DESC spec.homepage = "https://github.com/felipemendes/iHash" spec.license ...
# frozen_string_literal: true module Billing::Stripe::Webhooks::Invoices class PaymentSucceededOperation USER_DELIVERY_METHOD_BY_INTERVAL = { 'month' => 'monthly_subscription_paid', 'year' => 'annual_subscription_paid' }.freeze private_constant :USER_DELIVERY_METHOD_BY_INTERVAL def call...
require 'rails_helper' RSpec.describe "StaticPages", type: :system do describe "StaticPages/home" do before do visit root_path end it "signup link test" do click_on "新規登録" expect(current_path).to eq signup_path end it "login link test" do click_on "ログイン" expect(cur...
class CreateImports < ActiveRecord::Migration def change create_table :imports do |t| t.string :api_key t.string :resource_type t.text :mapping t.integer :record_count t.integer :success_count t.integer :error_count t.timestamps null: false end end end
class User < ApplicationRecord has_secure_password has_many :records, dependent: :destroy has_many :balances # rubocop:disable Rails/HasManyOrHasOneDependent has_many :points_expirations # rubocop:disable Rails/HasManyOrHasOneDependent validates :email, presence: true validates :password_digest, presence:...
require 'set' class Set #since the powerset of a given set is equal to the set of all subsets of that set, #it contains 2^n members, so instead of returning the actual powerset we return #an enumerator so it may be useful in cases of large sets def powerset as_array = to_a pset = Enumerator.new do |yie...
require 'minitest_helper' class TestSubscriptionRequest < MiniTest::Test include Zulu def teardown Zulu.redis.flushall end def subscribe_options(opts={}) { 'hub.mode' => 'subscribe', 'hub.topic' => '*/15 * * * *', 'hub.callback' => 'http://www.example.org/callback' }.merge(o...
module Synchronisable class AttributeMapper class << self def map(source, mappings, options = {}) new(mappings, options).map(source) end end def initialize(mappings, options = {}) @mappings = mappings @keep = options[:keep] || [] @only, @except = options[:only], opti...
class AddStationIdToServiceMaps < ActiveRecord::Migration[5.0] def change add_column :service_maps, :station_id, :integer end end
class UpdateContactInfoPage < SitePrism::Page set_url 'updateprofile.htm' element :first_name,'#customer\.firstName' element :last_name, '#customer\.lastName' element :address, '#customer\.address\.street' element :city, '#customer\.address\.city' element :state, '#customer\.address\.state' ...
require 'test_helper' class TopicTest < ActiveSupport::TestCase setup do @article = articles :sample_article @topic = topics :sample_topic @other_topic = topics :art_topic end test 'should be valid' do assert @topic.valid? end test 'name should be present' do assert @topic.valid? @t...
require 'time' class Customer attr_accessor :id, :first_name, :last_name, :created_at, :updated_at def initialize(hash) @id = hash[:id].to_i @first_name = hash[:first_name] @last_name = hash[:last_name] @created_at = ...
class Complaint < ActiveRecord::Base validates :user_email, :content, presence: true validates :user_email, email:true end
module Veeqo module Errors class RequestError < StandardError def message explanation end def explanation "A request to Veeqo API failed" end end end Error = Errors::RequestError end
# frozen_string_literal: true When(/^the user click on the Try us out button/) do initial_page = InitialScreen.new initial_page.try_us_out.click how_it_works_page = HowItWorksScreen.new %w[screen1 screen2 screen3 screen4].each do expect(how_it_works_page.indicator.displayed?).to be true swipe_right_to...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "precise32" config.vm.box_url = "http://files.vagrantup.com/precise32.box" config.vm.network :forwarded_port, guest: 3000, host: 3000 config.vm.network :private_network, ip: "192.168.33.10" config.ssh.forward_...
require 'spec_helper' describe OpenTx::Log::File do context 'data file taranis-x9d.csv' do before(:all) { @file = OpenTx::Log::File.new(data_file('taranis-x9d.csv')) } subject { @file } it { should have(1).sessions } its(:duration) { should be_within(0.1).of(85.2) } end describe '#opentx?'...
class ConfigFile attr_reader :destination def initialize(file) @destination = File.join(Dir.home, file) end def destination_empty? !File.exist?(@destination) end def to_s link = "#{name} -> #{destination}" if error "[#{Rainbow('error').red}] #{link}: #{Rainbow(error).red}" else...
class AddSongIdToReceptions < ActiveRecord::Migration def change create_table :song_receptions do |t| t.integer :song_id, :reception_id t.timestamps end end end
class ItemRevenueSerializer < ActiveModel::Serializer type :item_revenue attributes :id, :name, :description, :unit_price, :merchant_id, :revenue end
class Bear attr_accessor :bear_name, :type, :tummy def initialize(name, type) @bear_name = name @type = type @tummy = [] end def roar if @type == "grizzly" return "#{@bear_name} GRRRRR" else return "#{@bear_name} Ooo Errr" end end def take_fish(river) # fish = ri...
class Api def initialize text, tags, language @text = text @tags = tags @language = language @dictionary = {} @tool = LanguageTool.new(@language) @keywords = keywords @text end def get_result from, size result = {} result['images'] = search(from, size) suggested_tags = @keyw...
# UnbouncePage # # Calls the API and extracts detailed data about a specific page. # class UnbouncePage def initialize(api_interface, page_id) @api_interface = api_interface @page_id = page_id @data = {} end def fetch json = @api_interface.get(api_uri) @data = MultiJson.decode...
require_relative '../../../../spec_helper' describe 'govuk_rabbitmq::queue_with_binding', :type => :define do let(:title) { 'a_user' } let(:facts) {{ staging_http_get: 'curl', }} context 'missing routing key' do let(:params) {{ :amqp_exchange => 'an_exchange', :amqp_queue => 'a_queue', ...
class Meal attr_reader :item def initialize(args) @item = { "1" => args[:entree], "2" => args[:side], "3" => args[:drink], "4" => args.fetch(:dessert, "error"), "repeat" => args[:repeat]} end def get_order(input) return ["error"] if input.empty? parse_order(input) end private ...
class CreateBoatOptionTypes < ActiveRecord::Migration[5.0] def change create_table :boat_option_types do |t| t.string :rec_type t.string :name t.string :description t.integer :amount t.string :param_code end end end
class User < ActiveRecord::Base include Tokenable validates :full_name, presence: true validates :email, presence: true, uniqueness: true validates :password, presence: true, length: { minimum: 6 }, if: lambda{ new_r...
spec = Gem::Specification.new do |s| s.name = 'rack-unreloader' s.version = '2.1.0' s.platform = Gem::Platform::RUBY s.extra_rdoc_files = ["README.rdoc", "CHANGELOG", "MIT-LICENSE"] s.rdoc_options += ["--quiet", "--line-numbers", "--inline-source", '--title', 'Rack::Unreloader: Reload application when files c...
# frozen_string_literal: true RSpec.describe '`fakerbot list` command', type: :cli do it 'executes `fakerbot help list` command successfully' do output = `fakerbot help list` expected_output = <<~OUT Usage: fakerbot list Options: -h, [--help], [--no-help] # Displ...
class Project < ApplicationRecord extend FriendlyId friendly_id :name, use: :slugged validates_presence_of :name has_many :project_phases belongs_to :user end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. Please don't change it unless you know what you're doing. Vagrant.configure("2") do |config| config.vm.define "onesim" do |instance| instance.vm.hostname = "onesim" instance.vm.box = "bento/ubuntu-16.04" i...
class Entry < ActiveRecord::Base belongs_to :user def formatted_date self.created_at.strftime("%F") end end
class ApplicationController < ActionController::Base include ::ActionController::Cookies protected def bearer_token pattern = /^Bearer / header = request.headers["Authorization"] header.gsub(pattern, '') if header && header.match(pattern) end def auth_token cookies[:auth] || bearer_token ...
class KnightPenguin < Monster TIMER_WALK = 0.2 SPEED = 3 def initialize(chaos_penguin, camera) super(chaos_penguin, camera, "assets/enemy2.png",64,128); add_animation("WALK", [0,1,2,3]); add_animation("DIE", [0]); play_animation("WALK"); @position.x = Omega.width*...
require 'orchestrate' module Professor class Orchestra def initialize(client, app) @client = client @app = app @users = @app[:users] @sessions = @app[:sessions] @classes = @app[:classes] @assignments = @app[:assignments] end def valid_user?(user) !@users[user]...
class Category < ActiveRecord::Base has_many :category_cars has_many :cars, through: :category_cars end
# frozen_string_literal: true require 'jiji/configurations/mongoid_configuration' require 'jiji/utils/value_object' require 'jiji/web/transport/transportable' require 'jiji/utils/bulk_write_operation_support' module Jiji::Model::Graphing class GraphData include Mongoid::Document include Jiji::Utils::BulkWr...
# typed: strong # frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ffprober/version' Gem::Specification.new do |spec| spec.name = 'ffprober' spec.version = Ffprober::VERSION spec.authors = ['beanieboi'] spe...
class AddSortToItemloc < ActiveRecord::Migration def self.up add_column :itemlocs, :sort, :integer end def self.down remove_column :itemlocs, :sort end end
module Hateoas include ActionDispatch::Routing::PolymorphicRoutes # noinspection RubySuperCallWithoutSuperclassInspection def as_json(options = {}) json = super options return json if (options[:except] and options[:except].include? :url) or (options[:only] and not options[:only].inclu...
Pod::Spec.new do |s| s.name = "ReactiveCocoa" s.version = "2.5" s.summary = "The 2.x ReactiveCocoa Objective-C API: Streams of values over time" s.description = <<-DESC.strip_heredoc ReactiveCocoa (formally ReactiveCocoa or RAC) is an Objective-C fr...
class Interview < ApplicationRecord belongs_to :job_application, :foreign_key => :job_application_id validate :start_time_is_earlier validate :less_than_2_hours validates :start_time, :presence => true validates :end_time, :presence => true private def start_time_is_earlier errors.add(:start_t...
class AddCompanyToContacts < ActiveRecord::Migration def self.up rename_column :contacts, :first_name, :company_name rename_column :contacts, :last_name, :contact_name end def self.down rename_column :contacts, :company_name, :first_name rename_column :contacts, :contact_name, :last_name en...
# -*- encoding : utf-8 -*- module Network::NewCustomerHelper def new_customer_table(applications, opts = {}) table_for applications, title: 'ახალი აბონენტის განცხადებები', icon: '/icons/user--plus.png', collapsible: true do |t| t.title_action network_add_new_customer_url, label: 'ახალი განცხადება', icon: '/...
# encoding: utf-8 module Pakman module ManifestHelper def installed_template_manifest_patterns # 1) search . # that is, working/current dir # 2) search <config_dir> # 3) search <gem>/templates builtin_patterns = [ "#{Pakman.root}/templates/*.txt" ] config_patterns = [ "#{Fi...
class AddEntryIdToPdb < ActiveRecord::Migration def change add_column :pdbs, :entry_id, :string end end
# Set encoding to utf-8 # encoding: UTF-8 # # BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ # # Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). # # This program is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser Ge...
include FilestackRails::Transform include FilestackRails::Version module FilestackRails module ApplicationHelper def filestack_js_include_tag v2 = -> { javascript_include_tag('https://static.filestackapi.com/v3/filestack.js', type: 'text/javascript') } v3 = -> { javascript_include_tag('https://static...
class AdAccountCreative < ActiveRecord::Base serialize :colors has_attached_file :image do_not_validate_attachment_file_type :image def dl_image_url self.image.url end end
# This module is meant to be included into Models that have corresponding pages # in the old Culanth site, such as Articles, Issues, Fieldsights, etc. # # It provides methods for linking the same content from the old site to the new one, # and we'll use the LegacyNode model to intercept the old URLs and redirect them t...
module TestingCharacter def does_it_work? "#{name} yes" end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :feature_movie def feature_movie matching_movies = [] all_movies = Movie.all all_movies....
class CreateLiabilities < ActiveRecord::Migration def change create_table :liabilities do |t| t.string :category t.string :sub_category t.string :name t.integer :opening_principal_cents t.decimal :interest_rate t.integer :amortization t.string :payment_frequency t.i...
require File.dirname(__FILE__) + "/../spec_helper" describe MasterScenario do before(:each) do @admin = Factory(:admin) @master_scenario = Factory(:master_scenario, :user => @admin) end context "Validations" do before(:each) { @master_scenario = Factory.build(:master_scenario, :name => n...
require "rails_helper" feature "Admin deletes review" do scenario "admin deletes review succesfully" do review = FactoryGirl.create(:review) admin_user = FactoryGirl.create(:user) admin_user.make_admin sign_in_as(admin_user) visit site_path(review.site) click_on "Delete Review" expe...
module Astrails module Safe class Stream def initialize(parent) @parent = parent end def id @id ||= @parent.id end def config @config ||= @parent.config end def filename @parent.filename end def compressed? @parent ...
class CreatePosts < ActiveRecord::Migration[5.1] def change create_table :posts do |t| t.string :title t.text :content t.string :user_nickname t.string :thumnail_image t.string :voice_uploade_file t.integer :price #가격 t.timestamp :left_time #시간 t.integer :user_id #게...
# DISCLAIMER: # This software was produced in part by the National Institute of Standards # and Technology (NIST), an agency of the U.S. government, and by statute is # not subject to copyright in the United States. Recipients of this software # assume all responsibility associated with its operation, modification, # ...
module BackpackTF class UserListing # Process reponses from IGetUserListings class Response < BackpackTF::Response @response = nil @listings = [] def self.listings @listings = response['listings'].map do |attr| BackpackTF::UserListing.new(attr) end end en...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class BillingAddress < Address def set_address_type self.type ='BillingAddress' end end
require 'spec_helper' describe FlashingDotsTest do let(:english) { Language.create!(:name => 'English') } let(:user) { User.create!(:email => 'milan@milandobrota.com', :password => 'foobar') } let(:content) { Content.create!(:name => 'Abc', :body => 'body', :language => english)} it 'should know how to setup...
class MaleAnimal < Animal has_many :progeny, class_name: 'Animal', foreign_key: 'sire_id' def gender 'Male' end def model_name Animal.model_name end end
class Stack @head = nil def initialize end def top return @head.value end def push(value) newHead = Element.new(value) newHead.next = @head @head = newHead end def pop curr = @head if curr.ni...
namespace :load do DATA_FILE = ENV.fetch "DATA_FILE", "./lib/data/listens.json" SUBTOPIC_FILE = ENV.fetch "SUBTOPIC_FILE", "./lib/data/subtopics.json" desc "Load the subtopics.json file into the db" task sub_topics: :environment do sub_topics = JSON.parse File.read SUBTOPIC_FILE puts "Loading #{sub_top...
#http://railscasts.com/episodes/163-self-referential-association class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => "Occupation" end