text
stringlengths
10
2.61M
require 'spec_helper' describe "Questions" do before(:each) do @user = Factory(:user) integration_sign_in(@user) @problem = Factory(:problem, :user => @user) end describe "creation" do describe "failure" do it "should not make a new question" do lambda do visit new_pro...
# -*- encoding : utf-8 -*- require 'rails_helper' RSpec.describe Evaluation, type: :model do describe 'update_course_rating_and_count' do let!(:user) { FactoryGirl.create(:user) } let!(:course) { FactoryGirl.create(:course) } let!(:evaluation) do FactoryGirl.create(:full_evaluation, user: u...
# # 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_references_by_tag_name(tag_list) response = Excon::Response.new resp...
class CreateLabels < ActiveRecord::Migration def self.up create_table :labels do |t| t.string :name t.string :website t.string :email t.string :addres t.integer :viewed t.text :profile t.string :logo t.integer :created_by t.integer :updated_by t.timesta...
require 'rails_helper' require 'capybara/rails' require 'spec_helper' feature 'user add movies' do scenario "user can view new movie page" do user_views_new_movie_page end scenario "user can add new movie" do user_views_new_movie_page user_adds_new_movie end scenario "user must fill in all fiel...
class ResumesController < ApplicationController before_action :set_resume, only: [:show, :edit, :update, :destroy] access all: [:index, :show, :new, :edit, :create, :update, :destroy], user: :all def index if user_signed_in? @resumes = Resume.build_by(current_user) else redirect_to root_path,...
module TicTacToe class Cell attr_accessor :value #track the cell's value and intiialize it with a default value of '' def initialize(value = "") @value = value end end end
class AddUserArrayToBar < ActiveRecord::Migration def change add_column :bars, :user_ids, :integer, array: true, default: [] end end
Rails.application.routes.draw do get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' root to: 'rooms#show' resources :blogs # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
module Revolut module Api module Response class User attr_accessor :id attr_accessor :created_date attr_accessor :address attr_accessor :birth_date attr_accessor :first_name, :last_name, :phone, :email, :email_verified attr_accessor :state, :referral_code, :ky...
class RemoveColumnFromBatInningAgain < ActiveRecord::Migration[6.0] def change remove_column :bat_innings, :out end end
# Omega 3D Engine - by D3nX # Under MIT Licence # "The Omega Engine is a Gosu based game framework that claim # "to be fully open source and help everyone to developp faster # and more efficiently game in ruby" # Build 0.1 # Importing opengl & glu require 'opengl' require 'glu' OpenGL.load_lib GLU.load_lib include O...
# # Author:: Matt Eldridge (<matt.eldridge@us.ibm.com>) # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # module Fog module Network class Softlayer class Mock def get_subnet_price_code 42 end end class Real def get_...
require "spec_helper" describe Susanoo::Admin::DivisionsController do describe "routing" do it "routes to #index" do get("/susanoo/admin/divisions").should route_to("susanoo/admin/divisions#index") end it "routes to #new" do get("/susanoo/admin/divisions/new").should route_to("susanoo/admin...
class RenameAttachnmentToAttachment < ActiveRecord::Migration[5.0] def change rename_column :articles, :attachnment_id, :attachment_id rename_column :articles, :attachnment_type, :attachment_type end end
# Return values # Suppose we want to do some data analysis. # Eventually, I want to print the STANDARD DEVIATION of a set of numbers. # In other words, if I have a set of numbers like this: first_dataset = [93.0, 65.0, 87.0, 68.0, 2.0, 64.0, 36.0, 96.0, 45.0, 47.0] # Then I want to be able to do something like this:...
# frozen_string_literal: true module V1 module Helpers module Authentication extend Grape::API::Helpers def current_user return unless auth_token @current_user ||= JwtService.get_user(auth_token) end def authenticate! error!('401 Unauthorized', 401) unless curre...
require 'rails_helper' feature 'Images' do scenario 'prompts user to Sign In or Sign Up' do visit '/images' expect(page).to have_button('Sign In') expect(page).to have_button('Sign Up') end end
#encoding: utf-8 class New < ActiveRecord::Base STATUS = {:NORMAL => 0, :UNRELEASED => 1, :DELETED => 2} #新闻状态 0正常 1未发布 2已删除 end
class ChangeOgrnColumnOfClient < ActiveRecord::Migration def change change_column :clients, :ogrn, :text, limit: 15 end end
#!/usr/bin/ruby def my_show_hash(hash={}) hash.each do |key, array| key = "#{key}" array = "#{array}" puts key + " : " + array end end
require 'spec_helper' describe 'omnitruck instance packages' do describe package('ruby2.1') do it { should be_installed } end describe package('runit') do it { should be_installed } end end
require 'test_helper' class ApplicationHelperTest < ActionView::TestCase test 'app name' do ENV['APP_NAME'] = 'Test' assert_equal ENV['APP_NAME'], app_name end test 'title' do @title = 'test page' assert_equal [app_name, @title].join(' | '), title end end
require 'test_helper' require 'persistable/mogile_fs_adapter' class MogileFSAdapterTest < Test::Unit::TestCase def test_should_write_and_read_and_delete_persistable_objects adapter = Persistable::MogileFSAdapter.new(:domain => "mydomain", :tracker => "tracker.test.de:6001", :class => 'devel') data_to_persi...
Shindo.tests('TerremarkEcloud::Compute | catalog requests', ['terremark_ecloud']) do @catalog_format = { 'name' => String, 'uri' => String, 'catalogItems' => [{ 'name' => String, 'uri' => String }] } @catalog_item_format = { ...
shared_examples "assignable" do describe "Associations" do it { is_expected.to have_many(:assignments) } end describe "Assignments" do it "Can be assigned to a person" do person = build(:person) assignment = subject.assign_to(person) expect(subject.assignments.first).to eq(assignment) ...
class UsuarioSerializer < ActiveModel::Serializer attributes :id, :name, :email, :login end
require 'rails_helper' RSpec.describe RunTaskJob, type: :job do let!(:task) { create(:task) } it 'sleeps task.complexity seconds' do expect_any_instance_of(RunTaskJob).to receive(:sleep).with(task.complexity) RunTaskJob.perform_now end end
require 'rails_helper' describe "games/show.json.jbuilder", type: :view do before(:each) do allow(controller).to receive(:can?).and_return(true) @game = assign(:game, create(:game)) render end attributes = %w[ id state created_at updated_at url ] it "renders the following at...
require 'spec_helper' describe 'Delete event', js: true do let!(:user) { create(:user, :paul) } let!(:event) { create(:event, :tasafoconf, owner: user, users: [user]) } before do login_as user, event_path(event) end context 'without restriction' do before do click_with_alert "delete_event_id_...
# frozen_string_literal: false module JekyllImport module Importers class CloudScribeSql < Importer def self.require_deps JekyllImport.require_with_fallback(%w( rubygems fileutils safe_yaml unidecode tiny_tds )) end def self.spe...
require 'rails_helper' RSpec.describe UserDecorator do describe '#as_json' do let(:user) { stub_model User, first_name: 'Name', last_name: 'Surname', email: 'test@test.com' } subject { user.decorate.as_json } its([:full_name]) {should eq 'Name Surname'} end end
class CreatePayments < ActiveRecord::Migration def change create_table :payments do |t| t.integer :participant_id t.integer :item_id t.integer :price t.boolean :status t.timestamps end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "debian/testing64" # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about thei...
class AddSlugIndexToProposals < ActiveRecord::Migration[5.0] def change add_index :proposals, :slug Proposal.update_all(slug: nil) Proposal.find_each(&:save!) end end
# frozen_string_literal: true Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html devise_for :users, skip: %i[sessions registrations passwords] devise_scope :user do # Sessions. get 'login', to: 'devise/sessions#new', as: ...
require 'sinatra' require 'sinatra/reloader' enable :sessions helpers do def new_game session[:code] = [] session[:guesses] = 0 session[:gameover] = false session[:guesses] = [] 4.times do session[:code] << rand(1..4) end end end get '/' do...
Vagrant.configure("2") do |config| (1..3).each do |i| config.vm.define "hadoop#{i}" do |node| node.vm.box = "debian/contrib-jessie64" node.vm.hostname = "hadoop#{i}" node.vm.synced_folder '.\mount', '/hadoop_src' node.vm.provision "shell", path: "presetup.sh" node.vm.network "private...
require "rails_helper" describe RosterTransaction do it { should have_many(:transaction_line_items).dependent(:destroy) } it { should have_many(:fantasy_players).through(:transaction_line_items) } it { should have_many(:fantasy_teams).through(:transaction_line_items) } it { should define_enum_for(:roster_trans...
class CreateSupplierDnLine < ActiveRecord::Migration def change create_table :supplier_dn_line, id: false do |t| t.string :uuid, null: false t.string :supplier_dn_id, null: false t.integer :seq, null: false, default: 0 t.string :matnr, null: false t.string :ebeln t.string :ebel...
class WallbaseCollection < ActiveRecord::Base validates_presence_of :name, :material has_many :wallbase_style_types, dependent: :destroy has_many :wallbase_profiles, through: :wallbase_style_types, dependent: :destroy has_many :wallbase_collection_sections, dependent: :destroy accepts_nested_attributes_for...
# == Schema Information # Schema version: 20110313064440 # # Table name: subscribers # # id :integer(4) not null, primary key # device_id :string(255) # push_id :string(255) # created_at :datetime # updated_at :datetime # type :string(0) # active :string(0) # class Subscriber < Active...
class KeyPhrase < ActiveRecord::Base #==schema info #create_table "key_phrases", force: :cascade do |t| # t.integer "article_item_id", limit: 4, null: false # t.string "phrase_jpn", limit: 255, null: false # t.string "phrase_pronounce", limit: 255, null: false # t.datetime "created_at", ...
require 'test_helper' class MisurationsControllerTest < ActionDispatch::IntegrationTest setup do @user = User.create(nome:"Matteo",email:"matteo@gmail.com",password: "password") @sensors_group = SensorsGroup.create(nome:"velocità") @sensor = Sensor.create(mac: "3D:F2:C9:A6:B3:2F",url: "b", tipo: "a", la...
class RegistrationsController < Devise::RegistrationsController before_filter :update_sanitized_params, if: :devise_controller? def update_sanitized_params devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:name, :email, :password, :password_confirmation,:date_of_birth,:att_file)} devise_parameter_san...
class FontFinlandica < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/finlandica" desc "Finlandica" homepage "https://fonts.google.com/specimen/Finlandica" def install (share/"fonts").install "Finlandica-Italic[wght].ttf" (share/"...
require 'spec_helper' describe RegistrationsController do describe "#new" do before { get :new } subject { response } it { should be_success } it { should render_template :new } end describe "#create" do let(:params) do { registration: { email: 'test@example.com' } ...
class AddUserRefToProjectPhases < ActiveRecord::Migration[5.1] def change add_reference :project_phases, :user, foreign_key: true end end
# frozen_string_literal: true module Vedeu module Interfaces # Clear the named interface. # # @api private # class Clear include Vedeu::Common extend Forwardable def_delegators :geometry, :height, :width def_delegators :interf...
class Brewtap < Formula desc "my DESC" homepage "" url "https://github.com/pvegh/brewtap/archive/tag2.tar.gz" version "2" sha256 "c35e8afa57d9ddd2b04bf92cec47d8a1bf0f699d2073a8ce0a50c5430f02320c" def install bin.install "testecho.sh" end end
class Category < ApplicationRecord has_many :superpowers has_one_attached :photo end
require File.dirname(__FILE__) + "/../spec_helper" describe PasswordResetsController do def mock_user(stubs={}) @mock_user ||= mock_model(User, {:email => "test@test.com", :perishable_token => "abc123"}.merge(stubs)) end context "GET new" do it "should render the new template" do get :new r...
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'polisher/version' PKG_FILES = Dir.glob('{lib,spec}/**/*.rb') + Dir.glob('spec/data/*') + ['LICENSE', 'Rakefile', 'README.md'] Gem::Specification.new do |s| # Dynamically creat...
class Invitation < ActiveRecord::Base # constants VALID_PERIOD = 5.days STATUS = { expired: -20, failed: -10, normal: 0, verified: 10 } enum status: STATUS # validation validates :token, presence: true validates :email, presence: true validates :email, uniqueness: true validates :...
json.array!(@scenes) do |scene| json.extract! scene, :id, :review_id, :sort_order, :max_length, :name, :description, :scene_template_id json.url scene_url(scene, format: :json) end
class RenameSaleSince < ActiveRecord::Migration def change rename_column :companies, :sale_since, :sales_since end end
class House attr_accessor :name, :image_url attr_reader :id def initialize(house_details) @id = house_details['id'].to_i if house_details['id'] @name = house_details['name'] @image_url = house_details['image_url'] end def save sql = "INSERT INTO houses (name,image_url) VALUES ($1,$2) RETU...
name "windows-hostname" maintainer "Shay Bergmann" maintainer_email "shaybergmann@gmail.com" license "MIT" description "Sets hostname and FQDN of a windows node." long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "0.1.0" depends "windows"...
class GroupsController < ApplicationController after_action :verify_authorized def new @group = Group.new authorize @group end def create @group = Group.new(group_params) authorize @group if @group.save flash[:success] = "New group was created" redirect_to @group else ...
class CreateVehicles < ActiveRecord::Migration def change create_table :vehicles do |t| t.string :marca t.string :modelo t.string :ano t.string :color t.string :pasajeros t.string :tipo t.references :passenger, index: true, foreign_key: true t.timestamps null: fals...
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi module Models # # The branch build status # class BranchStatus # @return [Boolean] attr_accessor...
#!/usr/bin/env ruby # -*- coding: utf-8 -*- class Technique def act(master, enemy) end def perform(master, enemy) # 確率付きの実行 minus_accurates = master.changed_accuracy_rates.map{|a| a[0]} minus_accurate = minus_accurates.inject(0){|sum, x| sum + x} accurate = 100 - minus_accurate if rand(100 - 1...
class RenameAdActionColumnName < ActiveRecord::Migration def change rename_column :ad_actions, :adset_id, :ad_id end end
class Api::V1::UsersController < Api::V1::ApiController include FacebookAuthentication skip_before_action :authenticate_api_user def create if params[:facebook_token].present? create_account_from_facebook else create_raw_account end end private def create_raw_account endpoint_arg...
class Client::PostsController < ClientController before_action :set_post, only: [:show] # GET /posts # GET /posts.json def index @posts = Post.active. publish. order(starts_at: :desc). page(params[:page]). per(24) end # GET /posts/1 # GET /post...
FactoryBot.define do factory :product do name "Milk" description "Full fat milk from NZ." image "MyString" trait :invalid do name nil end end end
module PageObjects module Support module School module ResponsibleBody class EditPage < PageObjects::BasePage set_url '/support/schools/{urn}/responsible-body/edit' element :school_name_header, 'h1.govuk-heading-xl span.govuk-caption-xl' element :new_responsible_body_...
class Rack::OpenID private # Copied and tweaked from rack-openid gem def begin_authentication(env, qs) req = Rack::Request.new(env) params = self.class.parse_header(qs) session = env["rack.session"] unless session raise RuntimeError, "Rack::OpenID requires a se...
# 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 bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # ...
class AddIsRecoveryColumnToItemUse < ActiveRecord::Migration[5.2] def change add_column :item_uses, :recovery_lv, :integer add_index :item_uses, :recovery_lv end end
class AddResetTokenToAuthor < ActiveRecord::Migration def change add_column :authors, :reset_token, :string add_column :authors, :reset_token_expire, :datetime end end
require 'rails_helper' RSpec.describe SwipesController, :type => :controller do DatabaseCleaner.clean let(:user1) { FactoryGirl.create(:user)} before do DatabaseCleaner.clean login_with(user1) end after(:each) do DatabaseCleaner.clean end context "with user logged in" do it "should have...
module FakeDestroy extend ActiveSupport::Concern def destroy self.update(active: false) end end
OPERATORS = %w(+ - * /) def get_operator(str) operator = str.split.select do |v| OPERATORS.include?(v) end operator.shift.to_sym end def get_numbers(str, operator) str.scan(/\d/).map do |n| if operator == :/ n.to_f else n.to_i end end end def calculate(numbers, operator) numbe...
# --- Day 11: Corporate Policy --- # Santa's previous password expired, and he needs help choosing a new one. # To help him remember his new password after the old one expires, Santa has # devised a method of coming up with a password based on the previous one. # Corporate policy dictates that passwords must be exact...
class ContactsController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(params[:contact]) @contact.request = request if @contact ContactMailer.with(contact: @contact).hello_email.deliver_now else flash.now[:alert] = "Your message didn...
class Invard < ActiveRecord::Base belongs_to :ssend attr_accessible :invoice , :remark, :ssend_id, :ssend_attributes , :po_attributes validates_uniqueness_of :invoice end
# Copyright 2014 Square Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
class CreateAgents < ActiveRecord::Migration[5.1] def change create_table :agents do |t| t.string :name t.string :status t.boolean :admin, default: false t.timestamps end end end
require 'unit_helper' require "vendored_vagrant" require 'vagrant-lxc/container' describe Vagrant::LXC::Container do let(:name) { nil } subject { described_class.new(name) } describe 'container name validation' do let(:unknown_container) { described_class.new('unknown', cli) } let(:valid_container) {...
require 'rails_helper' RSpec.describe HomeController, type: :controller do describe 'GET #index' do it 'responds successfully with an HTTP 200 status code' do user = create(:user) sign_in user get :index expect(response).to be_success end it 'redirects to Sign in Path if not logge...
# encoding: utf-8 module ScriptNotifier class Processor attr_reader :context, :notice_queue, :result_queue, :running def run! ScriptNotifier.log("#{Time.now}: Setting up queues") setup_queues! ScriptNotifier.log("#{Time.now}: Ready to receive notification messages") @running = tru...
# frozen_string_literal: true require "spec_helper" class TestChannel < LiteCable::Channel::Base attr_reader :subscribe, :unsubscribe, :follows, :received def subscribed reject if params["reject"] @subscribe = true end def unsubscribed @unsubscribe = true end def receive(data) @received...
class FontPlusJakartaSans < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/plusjakartasans" desc "Plus Jakarta Sans" desc "Versatile modern type family" homepage "https://fonts.google.com/specimen/Plus+Jakarta+Sans" def install (sha...
class RemoveReservesAddShifts < ActiveRecord::Migration def change rename_table :reserves, :shifts end end
require 'sinatra/base' module Rainbow class Base < Sinatra::Base configure :development do register Sinatra::Reloader end not_found do json :error => 'Not found', :status => response.status end error Sinatra::BadRequest do json :error => 'Bad Request', :status => response.stat...
class AddCountToPaper < ActiveRecord::Migration def change add_column :papers, :favorites_count, :integer, :default => 0 add_column :papers, :publishes_count, :integer, :default => 0 end end
require 'interpreter' require 'permutation' require 'set' require 'test/unit' # TODO: Implement more of the tests suggested in https://eprint.iacr.org/2010/564.pdf class TestPermutation < Test::Unit::TestCase def setup @seed = Random.rand(2**64).to_s code = Permutation.new(5, @seed).generate_code ...
require 'data_generator/concerns/yaml_object' require 'active_support/core_ext/string' require 'data_generator/output' require 'pp' module DataGenerator class Generator extend YamlObject attr_reader :outputs, :factory, :quantity def initialize(attrs = {}) @outputs = attrs.fetch('outputs').collect ...
require 'xsd/qname' # {urn:example.com:echo-type}foo.bar class FooBar @@schema_type = "foo.bar" @@schema_ns = "urn:example.com:echo-type" @@schema_element = [["any", [nil, XSD::QName.new(nil, "any")]]] attr_accessor :any def initialize(any = nil) @any = any end end
# encoding: UTF-8 module CDI module V1 module Likes class CreateService < BaseCreateService record_type ::Like def initialize resource, user, options={} super user, options @resource = resource end def can_create_record? if @resource.nil? ...
require "test_helper" describe InviteRequest do before do @invite_request = InviteRequest.new( tournament: create(:tournament), user: create(:user) ) end it "must be valid" do @invite_request.valid?.must_equal true end end
require 'test_helper' class InventoryTest < ActiveSupport::TestCase setup do Inventory::THRESHOLDS = { drink_percentage: { gt: 50 }, food_cost: { lt: 60 } } end test 'in threshold greater than' do inventory = Inventory.new(drink_percentage: 55) assert inventory.in_threshold?(:...
class Bundle include Mongoid::Document field :title, type: String field :version, type: String field :license, type: String field :extensions, type: Array field :measures, type: Array field :records, type: Array validates_presence_of :name validates_presence_of :version def measure_defs Me...
require 'test_helper' class GameserverinfosControllerTest < ActionDispatch::IntegrationTest setup do @gameserverinfo = gameserverinfos(:one) end test "should get index" do get gameserverinfos_url, as: :json assert_response :success end test "should create gameserverinfo" do assert_differenc...
require 'rails_helper' RSpec.describe Product, type: :model do pending "add some examples to (or delete) #{__FILE__}" end describe '#id' do it 'id should be nil without save' do @product = Product.new expect(@product.id).to be_nil end it 'should be auto-assigned by AR for saved rec...
Spotterfly::Application.routes.draw do resources :albums, only: [:create, :new] resources :artists, only: [:index, :show, :create] root to: 'artists#index' end
# encoding: utf-8 #! /usr/bin/env ruby ## # Auteur CrakeTeam # Version 0.1 : Date : Mon Mar 17 09:42 2013 # require 'gtk2' require_relative 'Events' require_relative 'EventsOptions' require './Vue/Fenetres/FenetreAfficherScores' #===============================================================================# # ...
require 'acts_as_ontology_view_helper' module AssaysHelper include Stu::Acts::Ontology::ActsAsOntologyViewHelper #assays that haven't already been associated with a study def assays_available_for_study_association Assay.where(['study_id IS NULL']) end def assay_organism_list_item assay_organism re...
# frozen_string_literal: true class EtsPdf::Etl::TermBuilder < SimpleClosure TERM_HANDLES = { "automne" => "Automne", "ete" => "Été", "hiver" => "Hiver", }.freeze TERM_TAGS = { "anciens" => "Anciens Étudiants", "nouveaux" => "Nouveaux Étudiants", "tous" => nil, }.freeze def initializ...