text
stringlengths
10
2.61M
require_relative "builders/select_builder" module Sqlbuilder module Statements class Select include Builders::SelectBuilder def initialize(utils) @utils = utils @columns = [] @joins = [] end def column(column, from: nil, as: nil) @columns << {col: column,...
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? before_action :initialize_session before_action :load_cart protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: %i[name delivery_info prov...
class CreateFacebookLog < ActiveRecord::Migration def up create_table :facebook_logs do |t| t.string :url t.string :url_from_facebook t.text :params_from_facebook t.string :redirect_url t.string :code t.string :response t.text :response_body t.text :error t.da...
require 'spec_helper' describe "user creation" do let(:user) {User.new} context "whitelisting attributes" do it "allows mass-assignment of full_name" do expect(user).to allow_mass_assignment_of(:full_name) end it "allows mass-assignment of bio" do expect(user).to allow_mass_assignment_of(:bio) end ...
class AllpayController < ApplicationController skip_before_action :verify_authenticity_token, only: :callback # post /allpay/form/:order_id def form order = Order.find params[:order_id] transaction = CartService.create_transaction_from_order order @params = Allpay::Form.new(transaction, ClientB...
require 'spec_helper' require 'rails_helper' RSpec.describe Businesses do let(:category) do Category.new(attributes_for(:category)) end let(:location) do Location.new(attributes_for(:location)) end let(:business_attributes) do name = Faker::Name.unique.name { name: name, categor...
# Schema # t.string "first_name", null => false # t.string "last_name", null => false # t.string "email", :null => false # t.string "contact_number", :null => false # t.text "content", :null => false # t.datetime "created_at" # t.datetime "updated_at" class Enquiry < ActiveRecord::Base # Acces...
module HTTP class AuthenticationError < StandardError; end class Authenticated < Scraped def initialize super login end def self.ssl(ssl) raise AuthenticationError, 'ssl must always be enabled' unless ssl end private def login get '/' case @uri.host whe...
require "spec_helper" describe OrderNotifications do describe "new_order" do let(:mail) { OrderNotifications.new_order } it "renders the headers" do mail.subject.should eq("New order") mail.to.should eq(["to@example.org"]) mail.from.should eq(["from@example.com"]) end it "renders ...
#!/usr/bin/env ruby require 'test/unit' require 'lib/selenium' require 'net/http' require 'uri' require 'rubygems' require 'mysql' class SiteTimes < Test::Unit::TestCase @@SITE = (defined?(SITE) && SITE) || "http://localhost" @@DB_HOST = "util01.pro.viewpoints.com" @@DB_NAME = "statistician_producti...
class AddVisualCardUrlToReportDesign < ActiveRecord::Migration[4.2] def change at = DynamicAnnotation::AnnotationType.where(annotation_type: 'report_design').last unless at.nil? json_schema = at.json_schema.clone json_schema['properties']['visual_card_url'] = { type: 'string', default: '' } ...
# frozen_string_literal: true FactoryBot.define do factory :reminder do for_ticket # default if not trait is provided title { Faker::Lorem.word } note { Faker::Lorem.sentence } due_date { Faker::Time.forward(days: 2, period: :morning) } remind_interval { 0 } trait :for_ticket do assoc...
# Write a method called palindrome? which should accept a string as a parameter and return a boolean that indicates whether the string is a palindrome. A palindrome is a word that reads the same both forwards and backwards. Examples: eye, madam, racecar class Words def initialize(word) @word = word end de...
class PlacesController < ApplicationController def show @model = Place.find params[:id].strip if !@model.publish? raise ActiveRecord::RecordNotFound end @areas = @model.areas.includes(:area_category, :videos, :audios, :articles, :infos, :images).order_asc end end
class Appointment < ActiveRecord::Base has_and_belongs_to_many :employees, join_table: "appointments_employees", polymorphic: true accepts_nested_attributes_for :employees scope :sort_by_time, lambda { order('appointments.datetime') } scope :sort_by_customer_name, lambda { order('appointments.customer_last_name',...
Types::PostType = GraphQL::ObjectType.define do name "Post" description "A Post Type" field :id, !types.ID field :title, !types.String field :content, !types.String field :updated_at, !types.String field :user, !Types::UserType field :comments_count, !types.Int end
####### # NOTE! # - These tasks take hours # - `efficient_frontiers` task requires that the python critical line algoritm app be running (either on localhost or on internet) # - Overall `data_mapper` task is called from `rake load_data:efficient_frontiers_and_portfolios` ####### task data_mapper: ["data_mapper:ef...
# frozen_string_literal: true module Dynflow module Executors class Parallel require 'dynflow/executors/abstract/core' require 'dynflow/executors/parallel/core' # only load Sidekiq pieces when run in Sidekiq runtime (and the Sidekiq module is already loaded) require 'dynflow/executors/side...
require "rails_helper" RSpec.describe AvailabilityPolicy do describe "#manage?" do it "returns true for an admin user" do user = build_stubbed(:user_with_number, :admin) policy = described_class.new(user, user) result = policy.manage? expect(result).to be(true) end it "returns ...
class Seeker include Mongoid::Document include Mongoid::Timestamps field :uid, type: String field :targets, type: Array, default: [] field :followers, type: Array, default: [] def add_target target self.targets.delete target self.targets.push target self.save end def add_follower follower...
# Your code goes here! class Dog def name=(in_name) @name = in_name end def name @name end def bark puts "woof!" end end
class LikeSnapTemplate < ActiveRecord::Base validates :name, :text_overlay, presence: true scope :active, -> { where(active: true) } end
module Matchers extend RSpec::Matchers::DSL include Capybara::DSL matcher :have_success_message do |notice| match do |page| expect(page).to have_css(".alert-success", text: notice) end failure_message do |page| "expected #{page.text.inspect} to have success message #{notice.inspect}" ...
class AddNewToRecordings < ActiveRecord::Migration[5.2] def change add_column :recordings, :comments, :text add_column :recordings, :likes, :integer end end
# @param {Character[][]} grid # @return {Integer} def num_islands(grid) return 0 if grid == nil || grid.length == 0 number_of_islands = 0 0.upto(grid.length - 1) do |row| 0.upto(grid[row].length - 1) do |column| if grid[row][column] == '1' number_of_islands += depth_first_search(grid,row,column)...
require 'test_helper' class HandlerTest < ActiveSupport::TestCase test "transliteration" do a = Band.new a.name = "Häagen Dazs" possibilities = [ "haagen_dazs", # output of unidecode or normalization "hagen_dazs", # output of iconv ] assert possibilities.include?(a.generate_handle) ...
require 'spec_helper' describe 'knife cookbook site unshare' do it 'exits with status 0 when it succeeds' do cookbook = TestCook.create_cookbook unshare = run "knife cookbook site unshare #{cookbook.name} -y" cookbook.destroy expect(unshare.exitstatus).to eql(0) end it 'exits with status 100 w...
# -*- coding: utf-8 -*- require 'mui/gtk_extension' require 'mui/gtk_contextmenu' require 'plugin' require 'miku/miku' require 'gtk2' require 'uri' class Gtk::IntelligentTextview < Gtk::TextView extend Gem::Deprecate attr_accessor :fonts attr_writer :style_generator alias :get_background= :style_generator= ...
class Price include Mongoid::Document include Mongoid::Timestamps field :amount, type: Float field :effect_date, type: DateTime embedded_in :product end
class CustomerRoomsController < ApplicationController before_action :set_customer_room, only: [:show, :update, :destroy] # GET /customer_rooms def index @customer_rooms = CustomerRoom.all render json: @customer_rooms end # GET /customer_rooms/1 def show render json: @customer_room end # ...
class NewineServer < Sinatra::Application get '/events.json' do params[:since] = 1.year.ago if !params[:since] @events = Event.where('created_at > ?', params[:since]).order('created_at desc') @events = @events.where(:event_type => params[:types]) if params[:types] @events = @events.limit(100) jbuilder :"ev...
feature 'adding new bookmark' do scenario 'add new bookmark' do visit '/add' fill_in 'bookmark_title', with: 'SMASH' fill_in 'bookmark_url', with: 'http://www.elliesmash.com' click_button('Add') visit '/bookmarks' expect(page).to have_content("SMASH") end end
class AddEvaluationStrategyToChallenges < ActiveRecord::Migration def change add_column :challenges, :evaluation_strategy, :integer reversible do |dir| dir.up do Challenge.update_all(evaluation_strategy: 0) end end end end
require 'spec_helper' class IfPresent < Solid::ConditionalBlock def display(string) yield(!string.strip.empty?) end end describe Solid::ConditionalBlock do it_behaves_like "a Solid element" describe '#display' do let(:tokens) { ["present", "{% else %}", "blank", "{% endifpresent %}"] } subje...
require 'test_helper' class PostCommentsControllerTest < ActionDispatch::IntegrationTest setup do @post_comment = post_comments(:one) end test "should get index" do get post_comments_url, as: :json assert_response :success end test "should create post_comment" do assert_difference('PostComm...
# EventHub module module EventHub # Consumer class class Consumer < Bunny::Consumer def handle_cancellation(_) EventHub.logger.error("Consumer reports cancellation") end end end
class ProjectMedia < ActiveRecord::Base attr_accessor :quote, :quote_attributions, :file, :media_type, :set_annotation, :set_tasks_responses, :add_to_project_id, :previous_project_id, :cached_permissions, :is_being_created, :related_to_id, :relationship, :skip_rules include ProjectAssociation include ProjectMedi...
class SlackMessenger attr_reader :pull_request def initialize(pull_request) @pull_request = pull_request end def post if pull_request.nil? || channel_url.nil? return nil else uri = URI.parse(channel_url) params = { 'payload': payload } response = Net::HTTP.post_form(uri, p...
module BF module Instruction class OutputCharacter SAFE_OUTPUT = true SAFE_CHARACTERS = [9, 10, 13, (32..126).to_a].flatten def call(program) #binding.pry to_output = program.data[program.data_ptr] if SAFE_OUTPUT return unless SAFE_CHARACTERS.include?(to_outp...
require 'rails/generators' module BootstrapUnify class InstallGenerator < ::Rails::Generators::Base desc "Some description of my generator here" # Commandline options can be defined here using Thor-like options: class_option :my_opt, :type => :boolean, :default => false, :desc => "My Option" def co...
# frozen_string_literal: true module Helpers def dotloop_mock(request, request_type = :get, status_code = 200, query_params = '') endpoint = standard_endpoints(request) data_file = File.new(filename_to_path_json(endpoint, request_type.to_s)) WebMock .stub_request(request_type, endpoint_to_url(endpo...
require 'ipaddr' Puppet::Type.type(:certmonger_certificate).provide :certmonger_certificate do desc 'Provider for certmonger certificates.' confine exists: '/usr/sbin/certmonger' commands getcert: '/usr/bin/getcert' mk_resource_methods def initialize(value = {}) super(value) @property_flush = {} ...
# encoding: US-ASCII require 'ostruct' require 'binary_struct' module Iso9660 module Util ISO_DATE = BinaryStruct.new([ 'a4', 'year', # Absolute year. 'a2', 'month', 'a2', 'day', 'a2', 'hour', 'a2', 'min', 'a2', 'sec', 'a2', 'hun', 'c', 'offset' # 15-min inte...
require 'rails_helper' RSpec.describe Species, type: :model do describe 'Associations' do it { is_expected.to have_many(:monster_species) } it { is_expected.to have_many(:monsters).through(:monster_species) } end describe 'Attribute records' do it do expect(described_class.pluck(:name)).to cont...
require "helper" class MissingTest < Test::Unit::TestCase Photo = Class.new(Struct.new(:id)) test "adding it using extend" do imagery = Imagery.new(Photo.new(1001)) imagery.extend Imagery::Missing imagery.existing = "" assert_equal '/missing/photo/original.png', imagery.url end class WithMi...
class StashCli < Formula homepage "https://bobswift.atlassian.net/wiki/display/SCLI/Stash+Command+Line+Interface" url "https://bobswift.atlassian.net/wiki/download/attachments/16285777/stash-cli-3.9.0-distribution.zip?api=v2" version "3.9.0" sha1 "f615519894b194959754b9a7b5fb9bc03855dbcd" def install inr...
class Ability include CanCan::Ability def initialize(user) # Define abilities for the passed in user here. For example: # # user ||= User.new # guest user (not logged in) # if user.admin? # can :manage, :all # else # can :read, :all # end # # The first argume...
class User < ActiveRecord::Base validates_presence_of :username, :password validates_uniqueness_of :username has_many :bookmarks has_many :recommendations, foreign_key: "recipient_id" end
class AddUniqueIndexToWritings < ActiveRecord::Migration def change add_index :writings, [:author_id, :text_id], :unique => true end end
# frozen_string_literal: true require 'test_helper' class ReminderJobTest < ActiveJob::TestCase test 'Job performed' do @ticket = create(:ticket, :with_due_date) assert_enqueued_jobs 1 do ReminderJob.perform_later(@ticket) end end end
class ENV_BANG module Classes class << self attr_writer :default_class def default_class @default_class ||= :StringUnlessFalsey end def cast(value, options = {}) public_send(:"#{options.fetch(:class, default_class)}", value, options) end def boolean(value, op...
class SessionsController < ApplicationController before_action :require_current_user!, except: [:logout] def require_current_user! redirect_to cats_url if current_user end def new @user = User.new end def create user = User.find_by_credentials( params[:user][:username], params...
require 'spec_helper' describe Acfs::Resource::Locatable do let(:model) { MyUser } before do stub_request(:get, 'http://users.example.org/users/1') .to_return response id: 1, name: 'Anon', age: 12 stub_request(:get, 'http://users.example.org/users/1/profile') .to_return response user_id: 2, twi...
require 'optparse' class CommandBase def initialize(event, *args) @event = event @bot_args = args @server = { db_server: DiscordServer.find_by_discord_id(event.message.server.id), discordrb_server: event.message.server, } @invoker = { db_player: Player.find_by_discord_id(event.m...
require "minitest/autorun" require "minitest/pride" require "./lib/night_writer" class NightWriterTest < Minitest::Test def test_it_exists_and_has_attributes nite_writer = NightWriter.new assert_instance_of NightWriter, nite_writer assert_equal ARGV[0], nite_writer.file_in assert_equal ARGV[1], nite_...
require "test_helper" class MapTest < Minitest::Spec it "geocode" do response = Naver::Map.geocode(query: "불정로 6") response.must_be_instance_of Array response[0].point.x.must_equal 127.1052133 response[0].point.y.must_equal 37.3595316 end it "reverse_geocode" do response = Naver::Map.reverse...
class InvoiceItem < ActiveRecord::Base belongs_to :item belongs_to :invoice before_save :set_unit_price def self.find_invoice_items(params) where(invoice_id: params[:invoice_id]) end def self.find_invoices(params) find(params[:invoice_item_id]).invoice end def self.find_items(params) ...
class HotMastersController < ApplicationController before_action :set_hot_master, only: [:show, :edit, :update, :destroy] def input if params[:csv_file].blank? redirect_to(hot_masters_url, alert: INPUT_BLANK_ALERT) elsif params[:csv_file].original_filename.eql?('hot_master.csv') num = HotMaster...
require 'test_helper' class VoteResultsControllerTest < ActionController::TestCase include Devise::TestHelpers test 'should get show' do sign_in :user, create(:user) today = Date.today create(:vote_result, steam_app: create(:steam_app), created_at: today - 7) SteamGroup.stub :new, OpenStruct.new(...
# Value object to create objects for the quizzes page class QuizzesView def initialize(data) @data = data end def call return { result: 'No quiz found' }.to_json if @data.empty? result = final_scores result = [{ name: 'Lowest Score', data: result[:low] }, { name: 'Average Score', da...
module SearchHelper =begin Author: Auninda Rumy Saleque Method Name: generate_searched_data Purpose: This method returns the data necessary for populating the free text search results page. Input: query - The query string that was searched through the free text search box Outputs: Returns a Hash 'searchedData' wi...
class SmsSetting < ActiveRecord::Base belongs_to :company has_one :sms_credit , :dependent=> :destroy # later validations validates :sms_alert_no , :default_sms , numericality: { only_integer: true } validates :email , format: { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i , ...
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2023, by Samuel Williams. require 'console/compatible/logger' require 'console/terminal/logger' describe Console::Compatible::Logger do let(:io) {StringIO.new} let(:output) {Console::Terminal::Logger.new(io)} let(:logger) {Console::...
class RemoveColumnFromContacts < ActiveRecord::Migration[6.0] def change remove_column :contacts, :last_name, :string end end
desc 'Scrapes the list of MPs from parliament.nz' task :scrape do if ENV['DATABASE_URL'].nil? require 'dotenv' Dotenv.load end require './scraper' Parliament::MPScraper.new.call end
# frozen_string_literal: true # rubocop:disable Metrics/BlockLength require 'human_duration' RSpec.describe HumanDuration do it 'has a version number' do expect(HumanDuration::VERSION).not_to be nil end context 'Class Accessor Method' do context 'Using default compact mode' do ...
module Api module V1 class CommentsController < ApplicationController before_action :authenticate_user, only: %i[index create] # GET /api/v1/comments + Key def index render json: Comment.all end # POST /api/v1/comments + Key def create @comment = Comment.new(c...
class UserGroup < ActiveRecord::Base belongs_to :user belongs_to :company_group end
require 'rails_helper' RSpec.describe Contact, type: :model do it {should validate_presence_of(:email)} it {should validate_presence_of(:phone)} it {should validate_presence_of(:contact_type)} it {should belong_to(:contact_type)} end
require 'date' module Listable # Listable methods go here def format_description( description ) "#{description}".ljust(30) end def format_date_two( start_date, end_date ) dates = start_date.strftime("%D") if start_date dates << " -- " + end_date.strftime("%D") if end_date dates = "N/A"...
class AuctionsController < ApplicationController #This controller has no destroy method. #Auctions should only be destroyed along with #their chore or bounty. before_filter :require_user before_filter :require_admin, only: [:new, :edit] before_filter :clear_admin, only: [:create, :update] # GET /auctions ...
class AccountApi < Grape::API helpers BasicAPI::GeneralHelpers resources :accounts do before do @account = Account.find(params[:id].to_i) if params[:id] end desc '获取公开账目和自己创建的账目' params do use :pagination end get do accounts= pagination! Account.all.order('created_at DESC...
require './lib/constants' require './lib/board_navigation' class Board include Constants, Navigation attr_accessor :board attr_reader :direction def initialize(size) @board = Array.new(size) {|row| Array.new(size) {|element| element = " "}} @direction = DIRECTION end def size row_length = b...
require 'spec_helper' describe User do before do @user = FactoryGirl.create(:user) end it "authenticates with a valid email and password" do expect(@user.authenticate("foobar")).to eq(@user) end it "authenticates with an incorrect password" do expect(@user.authenticate("incorrect")).to be_false...
class Ability include CanCan::Ability def initialize(user) can :read, Page, user_id: user.id can :read, Comment, page: {user_id: user.id} end end
class Cms::AssetsController < Cms::BaseController before_action :load_cms_layout def render_css # avoid multiple retrieval due to several on-page web editors response.headers['Cache-Control'] = 'max-age=60, must-revalidate' render :text => @cms_layout.css, :content_type => 'text/css' end def rende...
class CreateLogs < ActiveRecord::Migration def change create_table :logs do |t| t.string :network t.string :channel t.text :line t.string :sender t.timestamps end end end
class CreateParticipations < ActiveRecord::Migration def change create_table :participations do |t| t.integer :exam_id t.integer :client_id t.string :relationship t.boolean :transfusion_within_three_months t.timestamps end end end
class RenamePrefectureColumnToRecitments < ActiveRecord::Migration[5.2] def change rename_column :recitments, :prefecture, :prefecture_code end end
class Bar < ChefResource::Struct property :x, Integer do def self.default 20 end end end class Foo < ChefResource::Struct property :bar, Bar do def self.default {} end end end class X < ChefResource::Struct property :foo, Foo do def self.default {} end end end x ...
class AddSlugToTag < ActiveRecord::Migration def change add_column :tags, :slug, :text end end
# frozen_string_literal: true class GraduationCensorForm def initialize(graduation) @graduation = graduation end def binary pdf.render end def pdf graduation = @graduation # Needs to be a local variable since the Prawn object runs the block below. Prawn::Document.new do date = graduat...
require 'spec_helper' require 'validation/test_validator' describe Definitions::Validation::Test do subject { described_class.new } context 'tests exist' do it 'reports success' do tests = "some tests" expect(subject.call(tests)).to be true end end context 'tests are empty' do it 'rai...
desc "Bump version number" task :bump do content = IO.read('_config.yml') content.sub!(/^version: (\d+)$/) {|v| ver = $1.next puts "At version #{ver}" "version: #{ver}" } File.open('_config.yml','w') do |f| f.write content end end
require 'test_helper' class QuestionTest < ActiveSupport::TestCase def setup @valid_q_params = { :prompt => 'This is a valid question because:', :answers_attributes => [ { :text => 'It has a prompt', :correct => false, }, { :text => 'It has an ans...
require "minitest/autorun" require_relative "rocket" class RocketTest < Minitest::Test # Write your tests here! def setup @rocket = Rocket.new end def test_name @rocket.name = 'johnny' result = @rocket.name assert_equal "johnny", result end def test_if_flying assert_equal false, @r...
include DataMagic Given(/^the user in (good standing|collections past due|collections past due one account) is logged in$/) do |user_type| DataMagic.load 'payment_options.yml' user_label = "payment_options_#{user_type.gsub(' ', '_')}" @payment_options_data = user_login(user_label) visit(AccountSummaryPage) e...
class Message < ApplicationRecord belongs_to :channel belongs_to :user, foreign_key: :author_id end
def palindrome?(string) return false if string.nil? string = string.to_s.gsub(/\W+/, '').downcase string.reverse == string end
class Card SPADE = 'SPADE' HEART = 'HEART' DIAMOND = 'DIAMOND' CLUB = 'CLUB' TYPE = [SPADE, HEART, DIAMOND, CLUB] def initialize(value, type) @value, @type = value, type end def >(another_card) @value > another_card.value end def ==(another_card) @value == another_card.value ...
class CreateJoinTableTalkTopic < ActiveRecord::Migration def change create_join_table :talks, :topics do |t| t.index [:talk_id, :topic_id] t.index [:topic_id, :talk_id] end end end
require 'rails_helper' describe Story do it { should have_many :comments } it { should validate_presence_of :title } it { should validate_presence_of :image } it { should validate_length_of :intro } end
module TheCityAdmin FactoryGirl.define do factory :user_skill, :class => TheCityAdmin::UserSkill do name "Teaching-Curriculum" skill_id 1046429013 end end end
# frozen_string_literal: true # rubocop:todo all require 'lite_spec_helper' describe Mongo::Srv::Monitor do describe '#scan!' do let(:hostname) do 'test1.test.build.10gen.cc' end let(:hosts) do [ 'localhost.test.build.10gen.cc:27017', 'localhost.test.build.10gen.cc:27018', ...
class SingularizeForeignKeys < ActiveRecord::Migration def change rename_column :relationships, :users_id, :user_id rename_column :relationships, :skills_id, :skill_id end end
n = ARGV[0].to_i n.times do |i| if i.even? puts i end end
class BookingsController < ApplicationController unless RAILS_ENV == "development" ssl_required :new, :edit, :create end # GET /bookings # GET /bookings.xml def index @bookings = Booking.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @bookings }...
raise "I can't handle this platform: #{RUBY_PLATFORM}" unless RUBY_PLATFORM =~ /darwin|linux/ file "pcre-7.8.tar.gz" => [] do sh 'curl -O ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.8.tar.gz' end file "pcre-7.8" => [ "pcre-7.8.tar.gz" ] do sh 'tar zxf pcre-7.8.tar.gz' end desc "Clean everyt...
require 'rails' module AppConfig class Railtie < Rails::Railtie initializer "app-config.configure_for_rails" do AppConfig.configure do |config| config.config_file = Rails.root.join("config", "config.yml") config.environment = Rails.env config.auto_reload = true if Rails.env == "dev...
require "socket" require "uri" module SimpleHttpServer class Server attr_reader :port, :web_root, :content_type_mappings DEFAULT_CONTENT_TYPE_MAPPINGS = { 'html' => 'text/html', 'txt' => 'text/plain', 'json' => 'application/json' } DEFAULT_CONTENT_TYPE = 'application/octet-stream' def initialize...